Android Shared Preferences With Multiple Activities
Solution 1:
You don't need any special manifest modificaiton to achieve that.
Assuming you have already saved preferences you can read those preferences at anytime doing something like I show bellow.
Write on Shared Preferences file:
SharedPreferencesprefs= getSharedPreferences("your_file_name", MODE_PRIVATE); SharedPreferences.Editoreditor= prefs.edit(); editor.putString("yourStringName", "this_is_the_saved_value"); editor.commit(); // This line is IMPORTANT. If you miss this one its not gonna work!
Read from Shared Preferences file:
SharedPreferencesprefs= getSharedPreferences("your_file_name", MODE_PRIVATE); Stringstring= prefs.getString("yourStringName", "default_value_here_if_string_is_missing");
You can use a default file to save/ read your preferences. Just replace the first line of the two code snippets above by something like: SharedPreferences prefs = getDefaultSharedPreferences(getApplicationContext());
Thats it! Check the Android Developers dedicated page to this matter, here.
Hope it was usefull. Let me know about it.
Solution 2:
You don't need to do anything special, other than make sure both activities are writing to/reading from the same file. Under the hood, preferences are just stored as an XML file.
So, your choices are:
1) Use PreferenceManager.getDefaultSharedPreferences() from both activities to write to the default file.
2) Use Context.getSharedPreferences() specifying a custom file name, and use the same name from both activities.
Solution 3:
Shared Preferences are just that, shared. As long as you properly save the preferences after editting them by calling Editor.commit(), they will be available in the future.
Post a Comment for "Android Shared Preferences With Multiple Activities"