假设想用SharedPreferences存取更复杂的数据类型(类、图像等),就须要对这些数据进行编码。
我们一般会将复杂类型的数据转换成Base64编码,然后将转换后的数据以字符串的形式保存在 XML文件里。
因此,须要使用第三方的jar包。
在本例中使用了Apache Commons组件集中的Codec组件进行Base64编码和解码。读者能够从例如以下的地址下载Codec组件的安装包。
以下是Product类的代码:
package eoe.mobile;
import java.io.Serializable;
// 须要序列化的类必须实现Serializable接口
public class Product implements Serializable{
private String id;
private String name;
private float price;<span style="font-family:Microsoft Yahei, Tahoma, Simsun;color:#444444;"><span style="font-size: 14px; font-weight: 700; line-height: 21px;">
</span></span>在保存Product对象之前,须要创建Product对象,并将对应组件中的值赋给Product类的对应属性。将Product对象保存在XML文件里的代码例如以下:
Product product = new Product();
product.setId(etProductID.getText().toString());
product.setName(etProductName.getText().toString());
product.setPrice(Float.parseFloat(etProductPrice.getText().toString()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
// 将Product对象放到OutputStream中
oos.writeObject(product);
mySharedPreferences = getSharedPreferences("base64", Activity.MODE_PRIVATE);
// 将Product对象转换成byte数组,并将其进行base64编码
String productBase64 = new String(Base64.encodeBase64(baos.toByteArray()));
SharedPreferences.Editor editor = mySharedPreferences.edit();
// 将编码后的字符串写到base64.xml文件里
editor.putString("product", productBase64);
editor.commit();
将图象保存在XML文件里的代码例如以下:
java代码:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 将ImageView组件中的图像压缩成JPEG格式,并将压缩结果保存在ByteArrayOutputStream对象中
((BitmapDrawable) imageView.getDrawable()).getBitmap().compress(CompressFormat.JPEG, 50, baos);
String imageBase64 = new String(Base64.encodeBase64(baos.toByteArray()));
// 保存由图像字节流转换成的Base64格式字符串
editor.putString("productImage", imageBase64);
editor.commit();
在本例中取了一个中间值50。
也就是从XML文件里读取Base64格式的字符串,然后将其解码成字节数组。最后将字节数组转换成Product和Drawable对象。装载Product对象的代码例如以下:
java代码:
String productBase64 = mySharedPreferences.getString("product", "");
// 对Base64格式的字符串进行解码
byte[] base64Bytes = Base64.decodeBase64(productBase64.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
// 从ObjectInputStream中读取Product对象
Product product = (Product) ois.readObject();<span style="font-family:Microsoft Yahei, Tahoma, Simsun;color:#444444;"><span style="font-size: 14px; font-weight: 700; line-height: 21px;">
</span></span>java代码:
String imageBase64 = mySharedPreferences.getString("productImage","");
base64Bytes = Base64.decodeBase64(imageBase64.getBytes());
bais = new ByteArrayInputStream(base64Bytes);
// 在ImageView组件上显示图像
imageView.setImageDrawable(Drawable.createFromStream(bais,"product_image"));<span style="font-family:Microsoft Yahei, Tahoma, Simsun;color:#444444;"><span style="font-size: 14px; font-weight: 700; line-height: 21px;">
</span></span>版权声明:本文博主原创文章。博客,未经同意,不得转载。
Android SharedPreferences复杂的存储
原文:http://www.cnblogs.com/lcchuguo/p/4758395.html