tags:

views:

67

answers:

2

I got a strange problem, that my app's SharedPreference seems lost some specific keys (not all) when the phone reboot.

Have you ever meet this problem? I used that key to store a serialized object and I did that 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) {

    }
}
A: 

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

  1. the code below is bad. it seems the edit() method returns a new object each time.

    settings.edit().putString(key, s);
    settings.edit().commit();
    
  2. If you are saving some serialized object bytes in the SharedPreference, Base64 it!

virsir
A: 

favs = (Favs ) deSerialize(value.getBytes());

DavidM