上一篇文章是写2.2之前的SharedPreferences存储对象和图片的使用方法。

本篇文章简单说下2.2之后的使用方法。

由于android SDK2.2提供Base64编码和解码库,所以我们不需要引包。

http://developer.android.com/reference/android/util/Base64.html可以参考官方资料

特别提醒:存储的类不能为activity的内部类,测试过了

以下是在OnStop函数中存储Product对象的代码

protected void onStop() {
try {

Product product = new Product();
product.id = etProductID.getText().toString();
product.name = etProductName.getText().toString();
product.price = Float.parseFloat(etProductPrice.getText()
.toString());
ByteArrayOutputStream baos = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(product);
mySharedPreferences = getSharedPreferences("base64",
Activity.MODE_PRIVATE);
String productBase64 = new String(
Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));

SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("product", productBase64);


editor.commit();
oos.close();


} catch (Exception e) {
setTitle("error:" + e.getMessage());
}
super.onStop();
}

下面是读取product对象并写数据的代码段

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etProductID = (EditText) findViewById(R.id.etProductID);
etProductName = (EditText) findViewById(R.id.etProductName);
etProductPrice = (EditText) findViewById(R.id.etProductPrice);

byte[] base64Bytes;
ByteArrayInputStream bais;
try
{

mySharedPreferences = getSharedPreferences("base64",
Activity.MODE_PRIVATE);

String productBase64 = mySharedPreferences.getString("product", "");

base64Bytes = Base64.decode(productBase64, Base64.DEFAULT);

bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois = new ObjectInputStream(bais);

Product product = (Product) ois.readObject();
etProductID.setText(product.id);
etProductName.setText(product.name);
etProductPrice.setText(String.valueOf(product.price));

ois.close();

}
catch (Exception e)
{
e.printStackTrace();
}

}

更多相关文章

  1. Android 自定义属性时TypedArray的使用方法
  2. android v7包 正常导入使用方法
  3. 【Android 异步操作】AsyncTask 异步任务 ( 参数简介 | 方法简介
  4. android 使用SharedPreferences保存对象
  5. Android 内功心法(番外)——写在设计模式前,面对对象编程基础

随机推荐

  1. android适配器之基于BaseAdapt自定义简单
  2. 修改 android 手机 hosts 文件的方法
  3. Android(安卓)GridView 分页加载数据
  4. Android(安卓)总结外置 内置SD卡路径问题
  5. android 浮动按钮
  6. Android实现按下Back键程序隐藏到后台,而
  7. android listview的下拉加载
  8. mono for android 获取手机照片或拍照并
  9. android获取经纬度和地方名称(baidu api)
  10. android 开源项目个人总结