我們知道SharedPreferences只能存取String和簡單類型的數據如int,boolean等,如果想用SharedPreferences存儲複雜類型的數據(比如圖片,自定義的對象等),就需要對這些數據編解碼。通常會將複雜類型的數據轉換成Base64編碼,然後將轉換後的數據以字符串的形式保存在 XML文件中。代碼如下:
public class SharedData {
private Context context;
private SharedPreferences shared;
public SharedData(Context context) {
this.context = context;
shared = context.getSharedPreferences("device_data",
Context.MODE_PRIVATE);
}
public void saveDeviceData(Device device) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try { //Device爲自定義類
// 創建對象輸出流,並封裝字節流
ObjectOutputStream oos = new ObjectOutputStream(baos);
// 將對象寫入字節流
oos.writeObject(device);
// 將字節流編碼成base64的字符串
String oAuth_Base64 = new String(Base64.encodeBase64(baos
.toByteArray()));
Editor editor = shared.edit();
editor.putString("device", oAuth_Base64);
editor.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public Device getDeviceData() {
Device device = null;
String productBase64 = shared.getString("devive", null);
// 讀取字節
byte[] base64 = Base64.decodeBase64(productBase64.getBytes());
// 封裝到字節流
ByteArrayInputStream bais = new ByteArrayInputStream(base64);
try {
// 再次封裝
ObjectInputStream bis = new ObjectInputStream(bais);
// 讀取對象
device = (Device) bis.readObject();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return device;
}
}
用到的Base64類來自commons-codec.jar包,下載地址:
http://commons.apache.org/proper/commons-codec/download_codec.cgi