Search code examples
javaandroidbundleonpause

What is better for my needs, onPause() or onSaveInstanceState()?


i have an app that has three pages, one of them is the main page. the user can enter in a few fields that i would like to save if the user goes to one of the two sub pages. i have been looking into the onPause() and into onSaveInstanceState(). i guess i just want a clear explanation on the two, and if onPause() is better and example of the code. this is what i ahve for onSaveInstanceState().

protected void onSaveInstanceState(Bundle outState) {
    // Save away the original text, so we still have it if the activity
    // needs to be killed while paused.

    outState.putDouble("quizPts",qpts);
    outState.putDouble("quizV",qvalue);
    outState.putDouble("tPts",tpts);
    outState.putDouble("tValue", tvalue);
    outState.putDouble("hPts", hpts);

so that is how i am setting up bundle, by giving it an ID and a value.

public void onRestoreInstanceState(Bundle outState) {
  super.onRestoreInstanceState(outState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  qpts = outState.getDouble("quizPts");
  qvalue = outState.getDouble("quizV");
  tpts = outState.getDouble("tPts");
  tvalue = outState.getDouble("tValue");
  hpts = outState.getDouble("hPts");

this is how i plan to retore it, the problem is i dont understand how to pass the Bundle around to restore it. i am setting the variables that i need to back to the variables that get set to the UI.

any advice would be great

thanks from a beginner androider


Solution

  • The best option will be a shared preference. The onpause is designed for attending your concerns when app is paused due to a phone call or something. But if you use shared preference it gives you the method for saving your data and recover it wit default values if the saved value is not available. This data will persist across user sessions (even if your application is killed). But it is not a good option if you are planning to save something other than primitive data types like bool,int etc.

    see http://developer.android.com/guide/topics/data/data-storage.html#pref