save the state when back button is pressed

Sindu picture Sindu · Aug 29, 2012 · Viewed 26.1k times · Source

I am developing an android app. If I press a back button the state of my application should be saved .What should i use to save the state ..am confused with all of these onPause(),onResume(), or onRestoresavedInstance() ??? which of these should i use to save the state of my application?? For eg when i press exit button my entire app should exit i have used finish() ?

   public void onCreate(Bundle savedInstanceState)
   {   

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    s1=(Button)findViewById(R.id.sn1);
    s1.setOnClickListener(this);
    LoadPreferences();
    s1.setEnabled(false);
    }

    public void SavePreferences()
 {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("state", s1.isEnabled());
       }
 public void LoadPreferences()
 {
     System.out.println("LoadPrefe");
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        Boolean  state = sharedPreferences.getBoolean("state", false);
        s1.setEnabled(state);
       }
 @Override
 public void onBackPressed()
 {
    System.out.println("backbutton");
    SavePreferences();
     super.onBackPressed();
 }

Answer

Andro Selva picture Andro Selva · Aug 29, 2012

What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,

@Override
public void onBackPressed() {

    super.onBackPressed();
}

And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.

Example,

private void SavePreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("state", button.isEnabled());
    editor.commit();   // I missed to save the data to preference here,. 
   }

   private void LoadPreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    Boolean  state = sharedPreferences.getBoolean("state", false);
    button.setEnabled(state);
   }

   @Override
public void onBackPressed() {
    SavePreferences();
    super.onBackPressed();
}

onCreate(Bundle savedInstanceState)
{
   //just a rough sketch of where you should load the data
    LoadPreferences();
}