问题
- How do I retrieve shared preferences that have been saved from a previous activity?
- Do I need to enable file writing or some other manifest modifications?
回答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:
SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE); SharedPreferences.Editor editor = 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:
SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE); String string = 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.
回答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.
回答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.
来源:https://stackoverflow.com/questions/12432585/android-shared-preferences-with-multiple-activities