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 = 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();
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();
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复杂存储,布布扣,bubuko.com
原文:http://blog.csdn.net/zhaoyazhi2129/article/details/38731779