Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Preferences get lost after shutting down device or killing the app

there are lots of questions out there related to shared preferences and the alternatives. My problem: when I shut down the device or kill the app, the shared preferences get lost. Please note that my code actually is working on Acer A500. But on my Motorola Xoom MZ604 it isn't working!!

First of all I try to restore my HashSet in onCreate. This method is called for sure and is implemented in a singleton.

public boolean restoreCollection(Context context){
    SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.restore_values), 0);
    if(settings.getStringSet(context.getString(R.string.collection), null) != null){
        collection = settings.getStringSet(context.getString(R.string.collection), null);
        return true;
    } 
    collection = new HashSet<String>();
    return false;
}

By calling onDestroy I save the HashSet. Even though it isn't given, that this method is called for sure, the Preferences get lost in any case, I have trying to save it in onPause with the same result.

public void saveCollection(Context context){
    SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.restore_values), 0);
    SharedPreferences.Editor e = settings.edit();
e.putStringSet(context.getString(R.string.collection), collection);
e.commit();
}

Has had anyone problems with Shared Preferences and the XOOM device,too or am I the only one? Perhaps something is fishy with my code but the data doesn't get lost on my Acer Tablet.

I've also tried PreferenceManager.getDefaultSharedPreferences(context) to get object of SharedPreferences

Thanks for your help, Chris

like image 686
Chris Avatar asked Mar 21 '12 11:03

Chris


People also ask

Does uninstalling app clear shared preferences?

The shared preference is definitely deleted when the application is uninstalled.

Can shared preferences be hacked?

It's not a secret that SharedPreferences is not a secure place to store sensitive data because the data is saved in simple key-value pairs in an XML file. In some cases, it can easily be hijacked.


1 Answers

I've figured out a solution that works both, on my Acer and on my XOOM device: you have to call clear() on the editor before committing new data:

public void saveCollection(Context context){
    SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.restore_values), 0);
    SharedPreferences.Editor e = settings.edit();
    e.clear();
    e.putStringSet(context.getString(R.string.collection), collection);
    e.commit();
}
like image 139
Chris Avatar answered Nov 15 '22 19:11

Chris