Shared Preferences, Android

To rembember data when view is finished, shared preferences can be used to keep data alive.

 

1. Place the code onCreate

sharedPreferences = MainActivity.activity.getSharedPreferences(this.getClass().getSimpleName(),
        MainActivity.MODE_PRIVATE);

Map<String,?> prefs = sharedPreferences.getAll();
for(Map.Entry<String,?> entry : prefs.entrySet()){
    MyObject myObject = new MyObject();
    if (myObject.deserialize(entry.getValue().toString()))
        myObjectList.add(myObject);
}

2. Place the code where you destroy the view:

public void save(){
    sharedPreferences.edit().clear().commit();
    for (MyObject myObject : myObjectList) {
        String data =  myObject.serialize();
        sharedPreferences.edit().putString(myObject.key, data).apply();
    }
}

 

Tags