您的位置:首页 > 移动开发 > Android开发

android SharedPreferences 存储对象

2016-11-09 16:20 375 查看
此方式可以保存将对象持久化到SharedPreferences,存储的对象需要实现Serializable接口。

private static SharedPreferences sPref;

private static SharedPreferences getPreference(Context ctx) {
if (sPref == null) {
sPref = ctx.getApplicationContext()
.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
}
return sPref;
}

private static Editor getEditor(Context ctx) {
return getPreference(ctx).edit();
}

private static void writeObject(Context ctx, String key, Object obj) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
String objBase64 = new String(Base64.encode(baos.toByteArray()));
getEditor(ctx).putString(key, objBase64).commit();
} catch (Exception e) {
Log.e("test", "saveObject error", e);
}
}

private static Object readObject(Context ctx, String key) {
try {
String objBase64 = getPreference(ctx).getString(key, null);
if (TextUtils.isEmpty(objBase64)) {
return null;
}
byte[] base64 = Base64.decode(objBase64);
ByteArrayInputStream bais = new ByteArrayInputStream(base64);
ObjectInputStream bis = new ObjectInputStream(bais);
return bis.readObject();
} catch (Exception e) {
Log.e("test", "readObject error", e);
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android