使用SharedPreferences保存对象

使用SharedPreferences保存对象

我们知道,SP可以保存像String和int这样的简单类型的数据,但不能直接保存对象。在需要保存对象的时候,就需要用到格式转换。

步骤:

1、将复杂数据(obj)转换为字节码;

ByteArrayOutputStream bos = new ByteArrayOutputStream();

ObjectOutputStream os = new ObjectOutputStream(bos);

os.writeObject(obj);

2、然后将字节码按Base64编码格式转换为String;

String bytesToHexString = new String(Base64.encode(bos.toByteArray(), Base64.DEFAULT));

3、

SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);

Editor editor = sharedPreferences.edit();

editor.putString(key, string);

editor.commit();

保存String;

注意,这段代码应该放到具体的调用方法中,不能作为全局的。SharedPreferences 是进行一个读写文件的操作,会出现无响应的情况。

4、使用时,拿到String数据

String string = sharedPreferences.getString(key, "");

5、将string按Base64解码格式转换字节码

byte[] stringToBytes = Base64.decode(string, Base64.DEFAULT);

6、将字节码转换为原始数据

ByteArrayInputStream bis=new ByteArrayInputStream(stringToBytes);

ObjectInputStream is = new ObjectInputStream(bis);

Obj obj = (obj)is.readObject();

以上,1~3是保存的操作,4~6是取出的操作。

另外,需要保存的对象需要使用Serializable接口进行实例化,否则会报NotSerializableException的异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值