Search code examples
androidandroid-layoutandroid-fragmentsandroid-activity

how to clear my SharedPreferences when my app is killed through task manager?


I'm using SharedPreferences to save the state of my CheckBox items in my ListView so that I don't lose the checked state when switching from FragmentActivity A to FragmentActivity B then back to FragmentActivity A. I want to clear my SharedPreferences if user exits the app.

My SharedPreferences is initialized in my BaseAdapter class like this:

private SharedPreferences sharedPreferences;
public static SharedPreferences.Editor editor;

I override onBackPressed() method in my FragmentActivity A and call

MyBaseAdapter.editor.clear().commit();

I am only able to clear my SharedPreferences if user exits the app by clicking the back button but if user kills the app through the task manager while the app is running, SharedPreferences is not cleared. So, when user opens the app again, the CheckBox items in my ListView are checked which should not be. The CheckBox items in my ListView should be unchecked when user opens the app. The problem is how do I clear my SharedPreferences if my app is killed by the user through task manager while the app is active or running?

I tried overriding onStop() method on my FragmentActivity A and call

MyBaseAdapter.editor.clear().commit();

but my SharedPreferences are deleted when I navigate from FragmentActivity A to FragmentActivity B. I don't want to lose the state of my CheckBox items in my ListView from FragmentActivity A when I switch between FragmentActivity A to FragmentActivity B and vice versa.


Solution

  • Why would you be using shared preferences if you want to clear them on your app launch?

    Shared Preferences are a way to store small preferences and read them later, for things such as settings.

    You could just define static variables in your activities and read them in your other ones. If you do want to clear the shared preferences, you should do it on the boot-up after your app is killed. Example of static variables:

    public static int i;
    if(I want to set a value){
    i = 1;
    }
    

    To access this in another activity:

    if(MainActivity.i == 1){
    //do something
    }