1. 程式人生 > >Android使用SharedPreferences儲存物件

Android使用SharedPreferences儲存物件

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) {
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;
}
例項化 bean

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;
}
}