我遇到了一个奇怪的问题,当手机重启时,我的应用程序的SharedPreference似乎丢失了一些特定的键(不是全部).
你有没有遇到过这个问题?我用那个键来存储一个序列化的对象,我在自己的Application类中做了.
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
调试完成后,我将在这里展示我自己的anwser,希望对其他人有帮助。
下面的代码很糟糕。看来 edit() 方法每次都会返回一个新对象。
Run Code Online (Sandbox Code Playgroud)settings.edit().putString(key, s); settings.edit().commit();
如果您要在 SharedPreference 中保存一些序列化对象字节,请使用 Base64!
| 归档时间: |
|
| 查看次数: |
1975 次 |
| 最近记录: |