Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between saving SharedPreferences in onPause() and onDestroy() methods

Tags:

android

I am trying to save an int variable int diff and I am not sure where I should save it,in onPause() or in onDestroy() methods. This variable is used in an fragment, attached to the MainActivity statically.

The code is basic:

@Override
public void onDestroy() {
    super.onDestroy();
    SharedPreferences sp = this.getActivity().getSharedPreferences("myPrefsName",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putInt("myPrefsInt",diff);
    editor.commit();
}

and for to retrieve it:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences sp = this.getActivity().getSharedPreferences("myPrefsName", Context.MODE_PRIVATE);
    diff = sp.getInt("myPrefsInt",1);
}
like image 866
Choletski Avatar asked Apr 24 '26 18:04

Choletski


1 Answers

There is no guarantee that onDestroy will ever be called; once an activity has been moved to the background, it is fair game to be killed if system resources are required, even without calling onDestroy. Therefore, you should save in onPause, instead. Note that, for state associated with a specific instance of an activity, onSaveInstanceState and onRestoreInstanceState may be more appropriate; however, onResume / onPause makes sense for global state like shared prefs.

like image 55
Michael Aaron Safyan Avatar answered Apr 26 '26 09:04

Michael Aaron Safyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!