package com.zb; import java.io.Serializable; public class Prodect implements Serializable { private String id; private String name; private float price; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
这里的对象必须是实现Serializable接口,否则会出错然后我们还要准备一个jar包就是commons-codec-1.4.jar,这个jar包负责将对象转换为base64的编码方式。
然我们看一下如何保存的:
package com.zb; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import org.apache.commons.codec.binary.Base64; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class SharedDemoActivity extends Activity { /** Called when the activity is first created. */ private Prodect prodect; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); readProduct(); referView(); } private void init() { prodect = new Prodect(); prodect.setId("1001"); prodect.setName("红河"); prodect.setPrice(6); } public void referView(){ TextView tv=(TextView) findViewById(R.id.share); tv.setText(prodect==null?"错":prodect.getName()); } public void readProduct() { SharedPreferences preferences = getSharedPreferences("base64", MODE_PRIVATE); String productBase64 = preferences.getString("product", ""); if (productBase64 == "") { init(); return; } //读取字节 byte[] base64 = Base64.decodeBase64(productBase64.getBytes()); //封装到字节流 ByteArrayInputStream bais = new ByteArrayInputStream(base64); try { //再次封装 ObjectInputStream bis = new ObjectInputStream(bais); try { //读取对象 prodect = (Prodect) bis.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void saveProduct() { SharedPreferences preferences = getSharedPreferences("base64", MODE_PRIVATE); //创建字节输出流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { //创建对象输出流,并封装字节流 ObjectOutputStream oos = new ObjectOutputStream(baos); //将对象写入字节流 oos.writeObject(prodect); //将字节流编码成base64的字符窜 String productBase64 = new String(Base64.encodeBase64(baos .toByteArray())); Editor editor = preferences.edit(); editor.putString("product", productBase64); editor.commit(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.i("ok", "存储成功"); } @Override protected void onStop() { saveProduct(); super.onStop(); } }
这样就可以存储复杂的对象了!