Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...