In an Activity_A, i have:
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreference settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
in Activity_B i have:
//changing the previously added **city** value
SharedPreferences settings = getSharedPreferences(Activity_A.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("city", myCity);
editor.commit();
in Activity_C i have:
SharedPreferences settings = getSharedPreferences(Activity_A.PREFS_NAME, 0);
String city = settings.getString("city", "default");
//here i am getting the previous value of **city**, not the updated 1 from Activity_B
But once i restart the application then it gives the correct value.
What am i doing wrong?
Thank You
In Activity C where you want to show the value, when do you get the value from the SharedPreferences?
You should get the SharedPreferences values in the onResume method i think because if you do this in the onCreate method no changes will be there if you co back to Activity C.
This is because the onCreate method will only be called once the Activity is first created. When you navigate back (away) from Activity C it goes on the backstack and is later restored using the onRestart or onResume. This means that the onCreate method is not called again.
So i suggest that you do the getting from the SharedPreferences in the onResume method.
Activity lifecylce: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
I'm right?
Rolf
Related
My app have mainactivity
User must set a password and it saved in shared prefence like this
settings = getSharedPreferences("NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("password", edpassstr);
editor.apply();
I can get this preference in another activity successfully
But I can't get it in the fragment
This is the code used to restore value from shared preference
settings = getActivity().getSharedPreferences("NAME", 0);
String passs = settings.getString("password", "");
The string passs is ="" inside fragment. Why?
How to get the string from shared preference in a fragment?
where are you calling getActivity() in your fragment? Because it will return null when it gets called before the fragment's onAttach method. In your fragment, try overriding the onAttach method, since it gets context as a parameter like so:
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
SharedPreferences settings = context.getSharedPreferences("NAME", 0);
}
If you want to use the shared preferences across the application. You should use applicationcontext instead of lifecycle owners (activity or fragments) context.
applicationcontext.getSharedPreferences(name, mode)
Declare as a global variable
SharedPreferences prefs;
SharedPreferences.Editor editor;
in onCreate() method declare as
prefs = getSharedPreferences("data", MODE_PRIVATE);
editor = getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("password", "xyz_password");
editor.apply();
You can get the value from shared preference using this way
prefs.getString(key,default Value);
prefs.getString("password", "Any value if you not get any value");
It's so easy I hope it's helpful to you...!
in my application, I used place picker.and data that place picker gave is sent to 3 different activities using shared preference.and show this data in TextView.problem is when I closed activity and again open that activity my data still visible in TextView.even when I cleared it in onDestroy().
here is my code for send data from place picker:
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("city_address", (String) cityAddress);
editor.putString("city_name", (String) city);
editor.commit();
Intent intent = new Intent(this, CleanlinessActivity.class);
startActivity(intent);
set data using this code in onCreate() of CleanlinessActivity
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
String n = settings.getString("city_name", "Enter Location");
String a = settings.getString("city_address", "");
cityname.setText(n);
cetlocation.setText(a);
and i cleared data using this code in CleanlinessActivity
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("city_address");
editor.clear().commit();
}
By closing the app you mean just clicking the home button then onDestroy() is never called, you can get a refresher of the android life cycles here
If what you are doing is simply clicking the home button then consider moving your code to the onStop() otherwise you need to commit() following the remove(...) The android documentation states "Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit() is called."
You have an instance of SharedPreferences called city_address which is having two fields or (Columns if we call it),but inside onDestroy()you are trying to to clear only one field of it called city_address,and the other field city_name field is left unchanged,if you want to completely remove the content of the city_address SharedPreferences use editor.clear().commit();
or``editor.clear().apply();`
I have 2 int in my navigation drawer, the value of whom changes upon clicking different button on different locations in the app.
I got the code to successfully increment and update them, but the problem is that they got reset when I open the app after closing or exiting it.
How can I make them stay there after getting updated?
If you want any code from my app, then please tell me.
Sorry for bad formatting of the question, but I have no idea how to do this and hence I haven't posted any code.
You must save the info in a persistent storage.
You can use SharedPreferences.
SharedPreferences prefs= getSharedPreferences("aName", MODE_PRIVATE);
//save the value
prefs.edit()
.putInt("nameOfTheValue", theValue).apply();
// get the data
prefs.getInt("nameOfTheValue", aDefaultValue);
You should save them as User SharedPreferences in onDestroy method.
public void onDestroy() {
super.onDestroy();
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//set the sharedpref
Editor editor = settings.edit();
editor.putInt("FIRST_INT", firstIntValue);
editor.putInt("SECOND_INT", secondIntValue);
editor.commit();
}
And then you can get them back wen needed:
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//get the sharepref
int firstInt = settings.getInt("FIRST_INT", 0);
int secondInt = settings.getInt("SECOND_INT", 0);
My string variables b,c,d,e,f stores the path of videos which I used in my gallery.But the problem is everytime my app shut down and restart again their values is lost and blank gallery is showed.I have tried making them static but through static they will retain the value for some time till the activity runs in background.Should I use onPause() and onResume() method so that they can retain their values.If yes plase suggest me code for that which i can use for retaining values of string variables when activity is closed.
SharedPreferences prefs = getSharedPreferences("bhu",0);
SharedPreferences.Editor editor = prefs.edit();
//Save the String value
editor.putString("val", b).commit();
editor.putString("val1", c).commit();
editor.putString("val2", d).commit();
editor.putString("val3", e).commit();
editor.putString("val4", f).commit();
b=prefs.getString("val", null);
c=prefs.getString("val1", null);
d=prefs.getString("val2", null);
e=prefs.getString("val3", null);
f=prefs.getString("val4", null);
You can use SharedPreferences to save the String values.
SharedPreferences prefs = getSharedPreferences(<Name>, <Mode>);
SharedPreferences.Editor editor = prefs.edit();
//Save the String value
editor.putString(<Key>, <StringValue>).commit();
Get the String value:
String str = prefs.getString(<key>, <DefaultValue>);
Please note that if you are not calling SharedPreferences in an Activity,you need to call getSharedPreferences through a Context.
[Edit]
if (prefs.getString("val", "Default").equals("Default")) {
editor.putString("val", b).commit();
}
Do it for other as well.
I have 3 Activities, let the Activity A is the main Activity from which B and C Activities are called. B is Activity with settings, and C is Activity with the main actions. I need to realize ToggleButton in B which is responsible for whether the device will vibrate after pressing the buttons in C. Thus, it is necessary to connect B and C. If using Intent, it is necessary to call the StartActivity (Intent)/StartActivityForResult (Intent) method. From this it follows that when pressing ToggleButton in B, the C will be called by B. And it is unnecessary to me. I need that when pressing ToggleButton "something" was remembered "somewhere", and then when the C is called it will be cause to device vibrating. How to solve this problem?
You can use SharedPreferences to store some states, eg:
SharedPreferences prefs = getSharedPreferences("myprefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key_string", "jack");
editor.putInt("key_int", 30);
editor.putBoolean("vibrator", false);
editor.commit();
Then you can read it when you need it:
SharedPreferences prefs = getSharedPreferences("myprefs", Context.MODE_PRIVATE);
String name = prefs.getString("key_string", "defaultName");
int age = prefs.getInt("key_int", 25);
boolean vib = prefs.getBoolean("vibrator", true);
Basically, SharedPreferences store key-value pairs. Read more about them here and here.
SharedPreferences is probably the best way to handle this. In Activity B create a SharedPreferences for vibrate, set to the boolean value "true" when the toggle is pressed, and then in Activity C check the SharedPreferences for said value and act accordingly.