onResume works even if activity is started

719 views Asked by At

I have an onPause and an onResume, see the two:

@Override
public void onResume(){
    super.onResume();
    String str = "";

    SharedPreferences prefs = this.getSharedPreferences(
            "com.example.app", Context.MODE_PRIVATE);
    for (int i = 0; i<prefs.getAll().size(); i++){
        str = prefs.getString(String.valueOf(i), "");
        meds.add(str);
        adap.add(str);
        adap.notifyDataSetChanged();}}


  @Override
public void onPause() {
    super.onPause();
    SharedPreferences prefs = this.getSharedPreferences(
            "com.example.app", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    for (int i = 0; i<meds.size(); i++){
        editor.putString(String.valueOf(i), meds.get(i));
        String str1 = editor.toString();
        String str = prefs.getString("0", "");

    }
    editor.commit();
}

Now this works fine whenever I really want to resume the activity -say, the user presses the backbutton.

However, when I completely restart the app (as in: shut down the program, run again), apparently onResume is called because my Data are set to those saved in onPause.

Am I just using the wrong method? When actually restarting the app, I want to start with my default data and not with what is saved in onPause.

2

There are 2 answers

3
Shobhit Puri On BEST ANSWER

OnResume is always called whenever you launch a new activity. You can see this from Activity LifeCycle. If you do not want to have your data when restarting the app, use isFinishing() method inside onPause and if it returns true clear everything before closing the Activity.

isFinishing() checks whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished.

2
Sreekanth On
  1. in onCreate() set the default values .
  2. in OnResume() get the latest values and update the the values of meds and adap
  3. in OnPause() save your preferences.. that is whatever you are doing now..
  4. you need not to clear the preferences them in onDestroy() , since there is no guarantee that the system call onDestroy()