使用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包的可以找我要


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值