SharedPreferences 스토리지 객체

1558 단어
이 방식은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;  
}  

좋은 웹페이지 즐겨찾기