Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences values do not persist?

I have a method as follows:

public static void addHighligtedDate(String date){
        prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0);
        Set<String> highlightedDates = prefs.getStringSet(Fields.HIGHLIGHTED_DATES, new HashSet<String>());
        highlightedDates.add(date);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putStringSet(Fields.HIGHLIGHTED_DATES, highlightedDates);
        editor.commit();
    }  

Now the scenario is this:
When I open the app add the dates to be highlighted, they are highlighted because SharedPreferences contains the values. When I press the home button to exit the app and come back, the values are still there.

However, when the app is removed from recents, the values go away. Is this normal behavior or am I doing something wrong?

Going over the docs:

This data will persist across user sessions (even if your application is killed).

like image 438
An SO User Avatar asked Aug 02 '26 13:08

An SO User


1 Answers

SharedPreferences is always deleted along with the app uninstall.

When you uninstall any application all the changes the application have made in your internal memory are revoked, that means your SharedPreference files, Other data files, Database file, Application gets removed automatically by the Android OS.

Check - how-to-remove-shared-preference-while-application-uninstall-in-android.

UPDATE:

However, when the application is killed or closed, the values from SharedPreferences persists. There is some problem in your code.

Change the method to -

public static void addHighligtedDate(String date){
        prefs = context.getSharedPreferences(Fields.SHARED_PREFS_FILE, 0);
        Set<String> highlightedDates = prefs.
        getStringSet(Fields.HIGHLIGHTED_DATES, new HashSet<String>());
        highlightedDates.add(date);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.putStringSet(Fields.HIGHLIGHTED_DATES, highlightedDates);
        editor.commit();
    }  

UPDATE:

public abstract Set getStringSet (String key, Set defValues)

Retrieve a set of String values from the preferences.

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

Parameters

key The name of the preference to retrieve.

defValues Values to return if this preference does not exist.

Also look for reference - sharedpreferences-does-not-save-on-force-close.

like image 172
My God Avatar answered Aug 04 '26 03:08

My God



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!