Android, SharedPreference lost when rebooting phone

I had a strange problem: when I rebooted the phone, my SharedPreference application lost some certain keys (not all).

Have you ever encountered this problem? I used this key to store a serialized object, and I did this in my own Application class.

public class Application extends android.app.Application {

static String key = "favs";
SharedPreferences settings;
public Favs favs;

@Override
public void onCreate() {
    super.onCreate();
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    String value = settings.getString(key, "");
    if (value != null && value.length() > 0) {
        try {
            Favs = (Favs ) deSerialize(value.getBytes());
        } catch (Exception ex) {
        }
    }
    if(favs == null)
        favs = new Favs ();
}

public void storeFavss() {
    if (favs == null)
        return;
    try {
        byte[] bytes = serialize(favs );
        if(bytes != null)
        {
            String s = new String(bytes);

            settings.edit().putString(key, s);
            settings.edit().commit();
        }
    } catch (Exception ex) {

    }
}
+5
source share
2 answers

After debugging, I will show my own anwser, hope it can help others.

  • the code below is bad. The edit () method seems to return a new object each time.

    settings.edit().putString(key, s);
    settings.edit().commit();
    
  • If you store several consecutive bytes of an object in a SharedPreference, Base64 it!

+2
source
favs = (Favs ) deSerialize(value.getBytes());
+1
source

All Articles