I am using the following code to save data to my Android application's shared preferences:
private SharedPreferences getOurSharedPreferences() {
return getSharedPreferences(SHARED_PREFS_FILENAME, MODE_PRIVATE);
}
SharedPreferences sharedPrefs = getOurSharedPreferences();
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(keyName, theString);
if (!editor.commit())
throw new RuntimeException("Unable to save new string.");
// Get it back as a test.
String s2 = getStringFromStorage(keyName);
Where SHARED_PREFS_FILENAME is a private final static string and keyName is the name of whatever key I'm currently using as a field name. The commit works fine, I don't get an exception. As you can see I added a test that retrieves the recently committed string and when I check it (s2) the value is fine. So I am not having any problems with shared preferences storage during the lifetime of my app. However, when I relaunch the application in the emulator the shared preferences storage area is empty and I can't find the values I stored in the last emulator session. I did some reading and as far as I can see the stored values should persist across sessions, apparently they are saved in an XML file belonging to the emulator. Yet I am having problems.
Can anyone tell me why my shared preferences storage values are not persist开发者_开发问答ing between Android emulator sessions?
-- roshcler
On the Target tab of the debug configuration Dialog window, do you have "Wipe User Data" ticked?
I had a similar problem. Try uninstalling the app and reinstall. Things can get corrupt in your shared preference files as you develop.
After I reinstalled my issues went away and I could see my persisted values across app lifecycles.
精彩评论