美文网首页
SharedPreferences 存储对象

SharedPreferences 存储对象

作者: goodl | 来源:发表于2017-06-12 09:17 被阅读0次

此方式可以保存将对象持久化到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;  
}  

相关文章

网友评论

      本文标题:SharedPreferences 存储对象

      本文链接:https://www.haomeiwen.com/subject/mzakqxtx.html