Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 SharedPreferences 儲存複雜物件

SharedPreferences 拿來存設定很方便,但它只吃簡單型別。想存 Map、List 這類複雜結構,思路是「先序列化,再編碼成字串」。最常見的組合是 ObjectOutputStream 加上 Base64。

寫入

// 將 map 轉為 byte[]
ByteArrayOutputStream toByte = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(toByte);
oos.writeObject(map);
// 對 byte[] 進行 Base64 編碼
String payCityMapBase64 = new String(Base64Coder.encode(toByte.toByteArray()));
// 儲存
editor.putString(KEY_CITY, payCityMapBase64);
editor.commit();

讀取

byte[] base64Bytes = Base64Coder.decode(prefer.getString(KEY_CITY, null));
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
map = (Map) ois.readObject();
boolean b = (Boolean) map.get(cityId);

兩個實務上的注意點

第一,被序列化的物件及其所有欄位型別都必須實作 Serializable,否則 writeObject 會丟出例外。第二,Base64 只是編碼而非加密,任何人取得 prefs 檔都能還原內容,因此敏感資料不該用這個方式存放;需要保密時請改用 Keystore 或加密後再寫入。另外反序列化來源的資料若可被外部竄改,也存在風險,最好只對自己寫入的內容做還原。

Copyright © Linux教程網 All Rights Reserved