7

using onSaveInstanceState(Bundle ..) and onRestoreInstanceState(Bundle ..)
was really good and work, but it is working when click Turn off button on Emulator.
Now, i want to save state and restore the saved data when below button used:
Emulator

I think it is possible to use OnPause() OR oOnStop(), if i am right, How to use it,
it will be enough to show me Java source of saving one boolean variable, and restore it,
Thanks.

kimo
  • 1,864
  • 5
  • 23
  • 29

6 Answers6

13

I had problems reading sharedPreferences after PowerOff when they were stored using onPause. The workaround was to call clear() first.

   public static final String PREFS_NAME = "MyPrefsFile";

   protected void onPause(){
        super.onPause();

        SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = settings.edit();
        // Necessary to clear first if we save preferences onPause. 
        editor.clear();
        editor.putInt("Metric", mMetric);
        editor.commit();
    }
Juan Mellado
  • 14,973
  • 5
  • 47
  • 54
Tim
  • 131
  • 1
  • 2
13

I would use onPause(), as onStop() is not guaranteed to be called. See the application fundamentals for details on the lifecycle.

To save and restore a boolean, I would use SharedPreferences. There is a code example on the data storage page that shows how to save and restore a boolean. They use onCreate() and onStop(), but I would use onResume() and onPause(), for the reasons I have already mentioned.

dave.c
  • 10,910
  • 5
  • 39
  • 62
5

the example :

public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){
   super.onCreate(state);
   . . .

   // Restore preferences
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean silent = settings.getBoolean("silentMode", false);
   setSilent(silent);
}

@Override
protected void onStop(){
   super.onStop();

  // We need an Editor object to make preference changes.
  // All objects are from android.context.Context
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putBoolean("silentMode", mSilentMode);

  // Commit the edits!
  editor.commit();
}

}

kimo
  • 1,864
  • 5
  • 23
  • 29
2

See Step 7 and Step 8 in the Android SDK notepad tutorial part 3. for an example saving the state to a sqlite DB (using a previously defined db-helper class.)

Macke
  • 24,812
  • 7
  • 82
  • 118
0

In that case you have no other option than making your state persistant in one of the ways described in Android DevGuide

mcveat
  • 1,416
  • 15
  • 34
0

you can just override onPause() in your activity say activtyA when you are navigating to another activity say activityB and override onResume() when u come back to the activityA.

sat
  • 40,138
  • 28
  • 93
  • 102