12

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();
 }
Gueorgui Obregon
  • 5,077
  • 3
  • 33
  • 57
Sindu
  • 215
  • 3
  • 6
  • 16
  • If the activity is closing, use onDestroy() – Aviral Aug 29 '12 at 05:23
  • What kind of application state you want to save? some textbox or list values? – VendettaDroid Aug 29 '12 at 05:24
  • Saving values for textbox or other important ui could be done with the help of sharedpreferences. So that, even if application exits or destroys, one can read the saved values from sharedpreferences. – VendettaDroid Aug 29 '12 at 05:26
  • 1
    i have a button which is in enabled state .If i press back i want the button should be in same enabled state but the button changes to disabled state ?how can i save that state ? – Sindu Aug 29 '12 at 05:35

2 Answers2

13

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();
}
Andro Selva
  • 53,910
  • 52
  • 193
  • 240
  • I understood the code .This is my application sir , where the user selects a destination via google map .The application tracks the present location of the user and when the user reaches the desination the alarm is snoozed.So i have to save the state of my button ,the GPS has to run in the background ,the alarm tone selected by the user has to be saved ,snooze button state has to be enabled . So as you told I have to define the SavePreferences and LoadPreferences for all buttons that i use???? – Sindu Aug 29 '12 at 05:55
  • yes you can save all primitive data types using Shared Preference. Modify the above code as per your requirement and you should be good to go. Get all the states of the button and save it with different key value. also maintain the tone name using string key and use it when you get back. – Andro Selva Aug 29 '12 at 06:00
  • can i use onPause or onResume so that my instance is saved instead of this SharedPreferences? – Sindu Aug 29 '12 at 06:10
  • But I think for that your app has to be in memory. If your app is killed by Android you will still loose the data. – Andro Selva Aug 29 '12 at 06:18
  • i have used many variables in my application like latitude,longitude.So for each and every value do i have to save the state using SharedPreferences?????Do i have any other method ? – Sindu Aug 29 '12 at 06:26
  • oh yes, for complex situations like this, you can use sqlite database. You can store and retrieve data from it. But trying to store it in memory for a long time is really a bad idea. – Andro Selva Aug 29 '12 at 06:31
  • i have called Loadpreferences in the first onCreate().But how can it store values if the app runs for the first time. It throws an error. Where should i place this load preferences ? – Sindu Aug 29 '12 at 07:10
  • If the apps runs the for the first time, it will take the default value as the actual value. For example, I have provided false as value for "state" key in the LoadPreference, so now what it does is, if the app is loaded for the first time it will give you false as the value, if not it will return the value which you stored previously using the savePreference method. – Andro Selva Aug 29 '12 at 07:22
  • I have edited the code. The button state is enabled before i press back and come out of the application. When i go back to the app again the button is getting disabled, which should stay enabled in my case. Can u pls chk the edited coding. Have i placed the load preferences call correctly ? – Sindu Aug 29 '12 at 07:36
  • Hey Sindu, I am really sorry. I have missed a line in the savePreference(), I have edited my answer. you have to add editor.commit(); at the end. only then your values will be saved to Preference. – Andro Selva Aug 29 '12 at 07:38
  • Are you by any chance from India? – Andro Selva Aug 29 '12 at 09:11
  • cool. Got it from the very use of your "Sir" here.. Atleast it is not required with me I guess. And yup, am from Chennai. Got stuck by your name Sindu. Just a guess you should be from India. – Andro Selva Aug 29 '12 at 09:53
  • Ya it was very useful... We infact completed the major part only with this. Few more are left :) Ll try to resolve it ourselves or will come up with doubts if we get struck.... – Sindu Aug 29 '12 at 10:11
  • No problem. Can contact me if you needed any help. And don't forget to click on the tick mark on the left side of this answer.. :) – Andro Selva Aug 29 '12 at 10:13
  • I want to save the place name after back is pressed.. I used this placeText = (EditText) findViewById(R.id.geocode_input); savePref//editor.putString("state1",placeText.getText().toString());LoadPref//placeText.setText(state1); // This is not working and throwing error... – Sindu Aug 29 '12 at 11:46
  • how much memory space this will take? – Hammad Nasir Oct 02 '17 at 18:26
4

you can use this way

public void onBackPressed() {
    // Save settings here   
};

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

save your application state in this method.

feupeu
  • 819
  • 7
  • 25
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177