0

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);
}
James
  • 181
  • 3
  • 13

2 Answers2

4

onPause() will always be called before your activity is placed in the background and/or destroyed, so you do not have to save state in onStop() and onDestroy() 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:

super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", Offset);
editor.commit();

You can read more here: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState

aspartame
  • 4,622
  • 7
  • 36
  • 39
  • That worked thanks, I forgot the commit(). Also thanks for the tip about the states. – James Dec 29 '11 at 15:36
  • I recommend using apply() instead of commit(). see this stackoverflow thread: https://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference – Dika Mar 08 '18 at 20:06
0

You will only need to save your offset in onResume() and set it to 0 when the activity is going to be destroyed, which you can tell by using isFinishing() in onPause(), like the following:

protected void onPause() {
    if(isFinishing()) {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("TheOffset", 0);
        editor.commit();
    }
}

...but I still have no idea what you intend to achieve.

neevek
  • 11,760
  • 8
  • 55
  • 73