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
The shared preference is definitely deleted when the application is uninstalled.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With