SharedPreferences 存储对象

我们知道SharedPreferences只能存取String和简单类型的数据如int,boolean等,如果想用SharedPreferences存储复杂类型的数据(比如图片,自定义的对象等),就需要对这些数据编解码。通常会将复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在 XML文件中。代码如下:

public class SharedData {

	private Context context;

	private SharedPreferences shared;

	public SharedData(Context context) {
		this.context = context;
		shared = context.getSharedPreferences("device_data",
				Context.MODE_PRIVATE);
	}

	public void saveDeviceData(Device device) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {   //Device为自定义类
			// 创建对象输出流,并封装字节流
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			// 将对象写入字节流
			oos.writeObject(device);
			// 将字节流编码成base64的字符串
			String oAuth_Base64 = new String(Base64.encodeBase64(baos
					.toByteArray()));
			Editor editor = shared.edit();
			editor.putString("device", oAuth_Base64);
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Device getDeviceData() {

		Device device = null;
		String productBase64 = shared.getString("devive", null);

		// 读取字节
		byte[] base64 = Base64.decodeBase64(productBase64.getBytes());

		// 封装到字节流
		ByteArrayInputStream bais = new ByteArrayInputStream(base64);
		try {
			// 再次封装
			ObjectInputStream bis = new ObjectInputStream(bais);

			// 读取对象
			device = (Device) bis.readObject();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return device;
	}
}
用到的Base64类来自commons-codec.jar包,下载地址:

http://commons.apache.org/proper/commons-codec/download_codec.cgi

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值