last seen activity not save in shared preferences - android

in first activity i have 3 button firs button go to subject list , second button show last seen activity
Im use this for last seen activity :
in subject list for each item save number in shared preferences and when user click on last seen number in subject list call and show last activity
this code work well but when i turn of phone or app not open for minutes last seen show nothing why?
please help me
in subject list class
shared = getSharedPreferences("count", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
public static int counter;
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent0 = new Intent(getApplicationContext(),Study.class);
startActivity(intent0);
counter=1;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
}
if (i == 1) {
counter=2;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent1 = new Intent(getApplicationContext(),Mo.class);
startActivity(intent1);
}
if (i == 2) {
counter=3;
SharedPreferences.Editor edit = shared.edit();
edit.putInt("count", counter);
edit.commit();
Intent intent2 = new Intent(getApplicationContext(),Sa.class);
startActivity(intent2);
}
in fist activity that contain last seen button :
case R.id.last_seen_btn:
if (SubjectActivity.counter==0){
Toast.makeText(getApplicationContext(), " nothing",
Toast.LENGTH_LONG).show();
}
if (SubjectActivity.counter==1){
Intent intent = new Intent(getApplicationContext(),Study.class);
startActivity(intent);
}
if (SubjectActivity.counter==2){
Intent intent = new Intent(getApplicationContext(),Mo.class);
startActivity(intent);
}
if (SubjectActivity.counter==3){
Intent intent = new Intent(getApplicationContext(),Sa.class);
startActivity(intent);
}

You shall use always the "application preferences" and best is to access them via the Application object. There is caching on SharedPreferences aand it's creating some issues some time.
Also update always the SharedPreferences before opening the Activity (if i == 0)
public class MyApp extends Application {
private SharedPreferences mMyPref;
#Override
public void onCreate() {
super.onCreate();
mMyPref = getSharedPreferences("my_pref_name", MODE_PRIVATE);
}
public SharedPreferences getMySharedPreferences(){
return mMyPref;
}
}
In your parts of code where you want to read/write just use
((MyApp)getApplicationContext()).getMySharedPreferences() ....
of of course create a local variable that gives you the possibility to work with it.

Related

Skip past Android Activity if it was already seen [duplicate]

I have an activity that i only want to run when the application is ran for the first time.
And never again. It is a facebook login activity. I only want to launch it once when the app is initially opened for the first time.
How do i go about doing this?
What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.
EDIT : In my onResume for the default Activity I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}
Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.
Post the following code within your onCreate statement
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, FirstLaunch.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
Replace FirstLaunch.class with the class that you would like to launch
something like this might work.
public class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
usage
boolean isFirstTime = MyPreferences.isFirst(CurrentActivity.this);
if (isFirstTime) {
NewActivity.show(CurrentActivity.this);
}
...
public class NewActivity extends Activity {
public static void show(Context context) {
final Intent intent = new Intent(context, NewActivity.class);
context.startActivity(intent);
}
}
SharedPreferences dataSave = getSharedPreferences("firstLog", 0);
if(dataSave.getString("firstTime", "").toString().equals("no")){ // first run is happened
}
else{ // this is the first run of application
SharedPreferences.Editor editor = dataSave.edit();
editor.putString("firstTime", "no");
editor.commit();
}
I had done this without Shared Prefrence...as I know shared prefrence consumes some memory so I used public static boolean variable in global class....First I made Global Class Appconfig...and then I made boolean static variable like this :
public class Appconfig {
public static boolean activity = false;
}
then I used this public static boolean variable into my welcome Activity class. I am Using License agreement page. which I have to use only at once in my application then never display further whenever i run the application. so i had put condtion in welcome activity...if the welcome class run first time so the static boolean variable is false...
if (Appconfig.activity == false) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this,LicesnceActivity.class);
startActivity(intent);
WelcomeActivity.this.finish();
}
if (Appconfig.activity == true) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
}
Now at Licesnce Activity class I made :
Appconfig.activity=true;
So whenever I run the Application the second activity "Main activity" run after Welcome activity not License Activity....
Declared in the globally
public int count=0
int tempInt = 0;
in your onCreate function past this code at first.
count = readSharedPreferenceInt("cntSP","cntKey");
if(count==0){
Intent intent = new Intent();
intent.setClass(MainActivity.this, TemporaryActivity.class);
startActivity(intent);
count++;
writeSharedPreference(count,"cntSP","cntKey");
}
Past these two method outside of onCreate
//Read from Shared Preferance
public int readSharedPreferenceInt(String spName,String key){
SharedPreferences sharedPreferences = getSharedPreferences(spName,Context.MODE_PRIVATE);
return tempInt = sharedPreferences.getInt(key, 0);
}
//write shared preferences in integer
public void writeSharedPreference(int ammount,String spName,String key ){
SharedPreferences sharedPreferences = getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, ammount);
editor.commit();
}
This is my code to bring the OnBoarding Activity for the first time. If it's not the first time then go directly to the Home Activity.
private void checkFirstOpen(){
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (!isFirstRun) {
Intent intent = new Intent(OnBoardingScreen.this, Home.class);
startActivity(intent);
finish();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun",
false).apply();
}

Android: How to maintain set data in the list view

In Activity A, I click a button to go to Activity B. I bring data using Bundle back to the Activity A and I managed to change a String value in the ListView. Then I go to another Activity C to manipulate another data. The problem is, when I get back again to the Activity A, the data from the Activity C is reflected in the ListView, but the previous data from the Activity B is gone.
Here's a code to the Activity B from the Activity A.
private void gotoRepeatWeeklyOptionActivity() {
Intent intent = new Intent(CreateNewAlarmActivity.this, RepeatWeeklyOptionActivity.class);
startActivity(intent);
finish();
}
This one is the method from the Activity A to the Activity C.
private void openAlarmToneOptionDialog() {
Intent intent = new Intent(CreateNewAlarmActivity.this, ChooseAlarmToneActivity.class);
startActivity(intent);
}
And this is a code that leads to the Activity A from the Activity B.
#Override
public void onBackPressed() {
Intent intent = new Intent(this, CreateNewAlarmActivity.class);
ArrayList<Integer> repeatStatusIntList = new ArrayList<>();
intent.putExtra(Keys.OPTION, Keys.OPTION_REPEAT);
if(cbRepeatEveryDay.isChecked()) {
super.onBackPressed();
intent.putExtra(Keys.VALUE, Keys.EVERY_DAY);
Toast.makeText(this, getString(R.string.alarm_will_repeat_every_day), Toast.LENGTH_SHORT).show();
} else if(allUnchecked()) {
super.onBackPressed();
intent.putExtra(Keys.VALUE, Keys.NO_REPEAT);
Toast.makeText(this, getString(R.string.alarm_will_never_repeat), Toast.LENGTH_SHORT).show();
} else {
for(int i=0; i<repeatStatusList.size(); i++) {
super.onBackPressed();
if(repeatStatusList.get(i).isChecked()) {
repeatStatusIntList.add(getRepeatStatusInt(repeatStatusList.get(i)));
intent.putIntegerArrayListExtra(Keys.KEY_REPEAT_STATUS_INTEGERS_LIST, repeatStatusIntList);
}
intent.putExtra(Keys.VALUE, Keys.ON);
}
Toast.makeText(this, getString(R.string.alarm_will_repeat) + getString(R.string.every) +
getAllRepeatDays(repeatStatusList), Toast.LENGTH_SHORT).show();
}
startActivityForResult(intent, RESULT_OK);
finish();
}
Finally, this is a code from the Activity C, which leads back to the Activity A.
btnSelectTone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CreateNewAlarmActivity.class);
intent.putExtra(Keys.OPTION, Keys.OPTION_ALARM_TONE);
intent.putExtra(Keys.VALUE, ringtone);
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
startActivityForResult(intent, RESULT_OK);
finish();
}
});
Here's a sample screen from the Activity A.
what Atif has suggested is one solution which is most desirable in your case.
Else you can use Shared Preferences like below. Get the SP instance and commit the data you want to share in editor
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
And this is how you can retrieve the shared pref data
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
Personally i would suggest you to surf more on developer.android.com or visit below link
https://developer.android.com/guide/topics/data/data-storage.html#pref
In future if you have large amount of data then above solution wont work.
Please follow below link for more options
How to pass the values from one activity to previous activity

How to send data from one activity to another activity

hi all i am new to android development my question is that how to call input edit text data in any activity where i required just like local storage in hmtl5 how to set value and get them where i required in any activity but not in the intent activity where i mentioned in the below example i want to show in some other activity means i need to get the values
here is my code
public class Autoinput extends Activity {
EditText Engines, Drivers;
Button next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autoinputvalues);
Engines = (EditText) findViewById(R.id.noofengines);
Drivers = (EditText) findViewById(R.id.noofdrivers);
next = (Button) findViewById(R.id.autoinputnext);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent autoinputscreen = new Intent (getApplicationContext(), autocoverage.class);
startActivity(autoinputscreen);
}
});
}
}
if we write put extra in intent it will go to that particular activity which we mention intent and there only we can get it my intention is to call in any activity and show them.
You should use shared preference. You should refer this link
You can do this in two ways, one is using Bundle and the another one throught Intent.
Using Bundle,
To Send:
Intent passIntent = new Intent(CurrentActivity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("Key", "Value");
passIntent.putExtras(bundle);
startActivity(passIntent);
To Receive:
Bundle bundle = getIntent().getExtras();
String recText = bundle.getString("Key");
Using Through Intent:
To Send:
Intent passIntent = new Intent(CurrentActivity.this, SecondActivity.class);
passIntent.putExtras("Key", "Value");
startActivity(passIntent);
To Receive:
String recText = getIntent().getExtras().getString("Key");
For your Code, in your FirstActivity
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position);
Intent passIntent = new Intent(CurrentActivity.this, SecondActivity.class);
passIntent.putExtras("Key", position);
startActivity(passIntent);
}
});
In SecondActivity,
details.setText(getIntent().getExtras().getString("Key"));
If you want the data to be destroyed after your application is closed or crashed you can use something like global variables: For example refer to this
On the other hand if you want your data to be persisted even after application crash, you can use shared preferences:
SharedPreferences pref;
pref=context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor=pref.edit();
Set data:
editor.putString("Engines", Engines.getText().toString());
editor.putString("Drivers", Drivers.getText().toString());
Then retrieve from anywhere:
String engines=pref.getString(("Engines",null);
String drivers=pref.getString(("Drivers",null);
if you want save your data and required in any activity must use Database or Share preference
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Vboolean IsTurnOn = preferences.getBoolean("Key", Default_Value);
To edit and set preferences
Editor editor = preferences.edit();
editor.putBoolean("Key", Value);
editor.commit();

How to launch activity only once when app is opened for first time?

I have an activity that i only want to run when the application is ran for the first time.
And never again. It is a facebook login activity. I only want to launch it once when the app is initially opened for the first time.
How do i go about doing this?
What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.
EDIT : In my onResume for the default Activity I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}
Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.
Post the following code within your onCreate statement
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, FirstLaunch.class));
Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
Replace FirstLaunch.class with the class that you would like to launch
something like this might work.
public class MyPreferences {
private static final String MY_PREFERENCES = "my_preferences";
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
}
usage
boolean isFirstTime = MyPreferences.isFirst(CurrentActivity.this);
if (isFirstTime) {
NewActivity.show(CurrentActivity.this);
}
...
public class NewActivity extends Activity {
public static void show(Context context) {
final Intent intent = new Intent(context, NewActivity.class);
context.startActivity(intent);
}
}
SharedPreferences dataSave = getSharedPreferences("firstLog", 0);
if(dataSave.getString("firstTime", "").toString().equals("no")){ // first run is happened
}
else{ // this is the first run of application
SharedPreferences.Editor editor = dataSave.edit();
editor.putString("firstTime", "no");
editor.commit();
}
I had done this without Shared Prefrence...as I know shared prefrence consumes some memory so I used public static boolean variable in global class....First I made Global Class Appconfig...and then I made boolean static variable like this :
public class Appconfig {
public static boolean activity = false;
}
then I used this public static boolean variable into my welcome Activity class. I am Using License agreement page. which I have to use only at once in my application then never display further whenever i run the application. so i had put condtion in welcome activity...if the welcome class run first time so the static boolean variable is false...
if (Appconfig.activity == false) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this,LicesnceActivity.class);
startActivity(intent);
WelcomeActivity.this.finish();
}
if (Appconfig.activity == true) {
Intent intent = new Intent();
intent.setClass(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
}
Now at Licesnce Activity class I made :
Appconfig.activity=true;
So whenever I run the Application the second activity "Main activity" run after Welcome activity not License Activity....
Declared in the globally
public int count=0
int tempInt = 0;
in your onCreate function past this code at first.
count = readSharedPreferenceInt("cntSP","cntKey");
if(count==0){
Intent intent = new Intent();
intent.setClass(MainActivity.this, TemporaryActivity.class);
startActivity(intent);
count++;
writeSharedPreference(count,"cntSP","cntKey");
}
Past these two method outside of onCreate
//Read from Shared Preferance
public int readSharedPreferenceInt(String spName,String key){
SharedPreferences sharedPreferences = getSharedPreferences(spName,Context.MODE_PRIVATE);
return tempInt = sharedPreferences.getInt(key, 0);
}
//write shared preferences in integer
public void writeSharedPreference(int ammount,String spName,String key ){
SharedPreferences sharedPreferences = getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, ammount);
editor.commit();
}
This is my code to bring the OnBoarding Activity for the first time. If it's not the first time then go directly to the Home Activity.
private void checkFirstOpen(){
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (!isFirstRun) {
Intent intent = new Intent(OnBoardingScreen.this, Home.class);
startActivity(intent);
finish();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun",
false).apply();
}

Android - Display button with sharedpreference value

I'm currently working in an Activity which saves text from Button1...button8.
But it not display text of button.i don't understand.
MainActivity=>
public void getName(){
SharedPreferences preferences = getSharedPreferences("sample",0);
int a=(preferences.getInt("num",0));
String ab=(preferences.getString("Name",""));
if(a==0){
button1.setVisibility(View.GONE);
button1.setVisibility(View.VISIBLE);
button1.setText(ab);
}
if(a==1){
button2.setVisibility(View.GONE);
button2.setVisibility(View.VISIBLE);
button2.setText(ab);
}
if(a==3){
button3.setVisibility(View.GONE);
button3.setVisibility(View.VISIBLE);
button3.setText(ab);
}
}
SetupActivity=>
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("Sample", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name", editText.getText().toString());
editor.putInt("num", myNum);
editor.commit();
Intent intent = new Intent(Setup.this, MainActivity.class);
startActivity(intent);
}
Check your Preference Names, you are using
getSharedPreferences("Sample", 0);
and
getSharedPreferences("sample",0);
not display text of button
That because (preferences.getString("Name","") return " " as default and this is probably the case.
In addition the lines:
button_.setVisibility(View.GONE);
button_.setVisibility(View.VISIBLE);
is really not make sense. you can drop the line:
button_.setVisibility(View.GONE);
First remove this line from the getName method
button_.setVisibility(View.GONE);
Then check out the KEY you are using to save the name of buttons in your case You are saving with the name of Sample and retrieving it as sample. Keep it mind key is case sensitive.
Now coming to other point in case you wrote key "Sample" just to demonstrate us the question. Before starting I would like to ask you where are you calling your method getName in mainActivity. But anyways here are the secure way of doing this:
When saving your button names add these lines
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("Sample", 0);
SharedPreferences.Editor editor = preferences.edit();
if(editText.getText().toString().length()>0){
editor.putString("Name", editText.getText().toString());
editor.putInt("num", myNum);
editor.commit();
Intent intent = new Intent(Setup.this, MainActivity.class);
startActivity(intent);}
}
and in getName method just do this
public void getName(){
SharedPreferences preferences = getSharedPreferences("sample",0);
int a=(preferences.getInt("num",0));
String ab=(preferences.getString("Name",""));
if(a==0){
button1.setVisibility(View.VISIBLE);
button1.setText(ab);
}
if(a==1){
button2.setVisibility(View.VISIBLE);
button2.setText(ab);
}
if(a==3){
button3.setVisibility(View.VISIBLE);
button3.setText(ab);
}
}

Categories

Resources