在Android開發過程中有時需要用到一些簡單的數據保存。
在系統自帶的sharedpreferences中提供了一些列的數據類型,但有時候需要保存一個List集合,系統則沒有現成的方法:
以保存場景爲例:
public static String SceneList2String(List SceneList)
throws IOException {
// 實例化一個ByteArrayOutputStream對象,用來裝載壓縮後的字節文件。
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 然後將得到的字符數據裝載到ObjectOutputStream
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
byteArrayOutputStream);
// writeObject 方法負責寫入特定類的對象的狀態,以便相應的 readObject 方法可以還原它
objectOutputStream.writeObject(SceneList);
// 最後,用Base64.encode將字節文件轉換成Base64編碼保存在String中
String SceneListString = new String(Base64.encode(
byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
// 關閉objectOutputStream
objectOutputStream.close();
return SceneListString;
}
@SuppressWarnings("unchecked")
public static List String2SceneList(String SceneListString)
throws StreamCorruptedException, IOException,
ClassNotFoundException {
byte[] mobileBytes = Base64.decode(SceneListString.getBytes(),
Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
mobileBytes);
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
List SceneList = (List) objectInputStream
.readObject();
objectInputStream.close();
return SceneList;
}
最後通過
SharedPreferences mySharedPreferences= getSharedPreferences("scenelist", Context.MODE_PRIVATE);
Editor edit = mySharedPreferences.edit();
try {
String liststr = Utils.SceneList2String(MyApp.scenesList);
edit.putString(Constants.SCENE_LIST,liststr);
edit.commit();
} catch (IOException e) {
e.printStackTrace();
}
SharedPreferences sharedPreferences= getActivity().getSharedPreference ("scenelist", Context.MODE_PRIVATE);
String liststr = sharedPreferences.getString(Constants.SCENE_LIST, "");
try {
showSceneList = Utils.String2SceneList(liststr);
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
進行保存獲取。