1、将要保存的对象进行序列化实现implements Serializable接口
2、给序列化接口配置ID serialVersionUID,如果没有配置ID后面版本对象如做改变,将和以前版本冲突,ID要在工程中唯一,可以使用eclipse自动生成
3、将序列化对象转换成Base64格式String进行保存
4、获取对象将保存的Base64格式String转换成对象获取
Java代码:
保存对象
protected boolean setObjectToShare(Context context, Object object,
String key) {
// TODO Auto-generated method stub
SharedPreferences share = PreferenceManager
.getDefaultSharedPreferences(context);
if (object == null) {
Editor editor = share.edit().remove(key);
return editor.commit();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
} catch (IOException e) {
e.printStackTrace();
return false;
}
// 将对象放到OutputStream中
// 将对象转换成byte数组,并将其进行base64编码
String objectStr = new String(Base64.encode(baos.toByteArray(),
Base64.DEFAULT));
try {
baos.close();
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SharedPreferences.Editor editor = share.edit();
// 将编码后的字符串写到base64.xml文件中
editor.putString(key, objectStr);
return editor.commit();
}
获取对象
protected static Object getObjectFromShare(Context context, String key) {实例化 bean
SharedPreferences sharePre = PreferenceManager
.getDefaultSharedPreferences(context);
try {
String wordBase64 = sharePre.getString(key, "");
// 将base64格式字符串还原成byte数组
if (wordBase64 == null || wordBase64.equals("")) { // 不可少,否则在下面会报java.io.StreamCorruptedException
return null;
}
byte[] objBytes = Base64.decode(wordBase64.getBytes(),
Base64.DEFAULT);
ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
// 将byte数组转换成product对象
Object obj = ois.readObject();
bais.close();
ois.close();
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
package com.SharedPreferences;
import java.io.Serializable;
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2421263553592651152L;
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
}