I have an app that doesn't save shared preferences. I have tried using both commit()
and apply()
to save these preferences, but they are not saved once the application closes. If I change screens in my app, the changes are made but are lost when the app restarts.
Static method called when the app starts:
static {
prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.getContext());//MainActivity.getContext().getSharedPreferences("LocationTimer", Context.MODE_PRIVATE);
editor = prefs.edit();
if(!prefs.contains("totalLocations")) {
prefs.edit().putInt("totalLocations", 0).commit();
}
if(prefs.getInt("totalLocations", 0) == 0) {
for (int i = 1; i <= COUNT; i++) {
addItem(createLocationItem(i));
}
Log.i("PREFERENCES", "CREATED 1 LOCATION");
} else {
for (int i = 1; i <= prefs.getInt("totalLocations", 1); i++) {
addItem(new LocationItem(String.valueOf(i), "Location " + String.valueOf(i), prefs.getString(String.valueOf(i), "")));
}
Log.i("PREFERENCES", "LOADED LOCATION(S)");
}
Log.i("PREFERENCES", "LOADED " + String.valueOf(prefs.getInt("totalLocations", 1)) +" LOCATION(S)");
}
The message logged is "PREFERENCES: LOADED LOCATION(S)" and not "PREFERENCES: CREATED 1 LOCATION" so I know the item is being loaded and not simply created.
Method called when any item is created/loaded:
public static void addItem(LocationItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
saveStringToPreferences(item.id, item.details);
editor.putInt("totalLocations", ITEMS.size());
editor.apply();
Log.i("PREFERENCES", "CONTAINS " + String.valueOf(prefs.getInt("totalLocations", 1)) +" LOCATION(S)");
Log.i("ITEMS", "CONTAINS " + String.valueOf(ITEMS.size()) +" LOCATION(S)");
}
How I can tell this is saving the preferences while the app is already loaded is the above messages display other numbers besides one. One is the amount shown when the app loads.
Thanks for any help and suggestions. If you have any questions, please post and I will respond as soon as possible.