Basically I have a list and I need to remember the offset and load the offset value every time the Activity is restored unless the Activity completely destroyed.
//Inside onCreate
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Offset = settings.getInt("TheOffset", 0);
//End onCreate
@Override
protected void onPause() {
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", Offset);
}
@Override
protected void onStop() {
super.onStop();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", Offset);
}
@Override
protected void onDestroy() {
super.onDestroy();
//settings.getInt("TheOffset", 0);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", 0);
}
onPause()will always be called before your activity is placed in the background and/or destroyed, so you do not have to save state inonStop()andonDestroy()as well.For the state to be preserved in SharedPreferences, you need to add
editor.commit()after writing the value. Otherwise it won’t be stored. Like this:You can read more here: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState