使用SharedPreferences保存序列化对象

我们通常会将复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在 XML文件中。

package com.example.animation.util;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;


import org.apache.commons.codec.binary.Base64;


import com.example.animation.AIDL.Book;


import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.util.TypedValue;


public class CommonUtil {


public static int dpToPx(Resources res, int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics());
}


public static int spToPx(Resources res, int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, dp, res.getDisplayMetrics());
}


public static void saveObj(Context context, String name, Object object) {
SharedPreferences preferences = context.getSharedPreferences(name, Activity.MODE_PRIVATE);


Editor edit = preferences.edit();
ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();


ObjectOutputStream objectOutputStream;
try {
objectOutputStream = new ObjectOutputStream(outPutStream);
objectOutputStream.writeObject(object);
byte[] encodeBase64 = Base64.encodeBase64(outPutStream.toByteArray());


String objString = new String(encodeBase64);
edit.putString(name, objString);
edit.commit();
} catch (IOException e) {
e.printStackTrace();
}
}

public static Object getObj(Context context,String name){
SharedPreferences sharedPreferences  = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
String objString = sharedPreferences.getString(name, "");

if (objString == null|| objString == "") {
return null;
}
byte[] bt = Base64.decodeBase64(objString.getBytes());
ByteArrayInputStream input = new ByteArrayInputStream(bt);

Object object = null;
try {
ObjectInputStream inputStream = new ObjectInputStream(input);


object = inputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return object;
}

}

此次使用了jar包 ,commons-codec-1.4.jar,需要此jar包的可以找我要


你可能感兴趣的:(自定义原创)