1. 程式人生 > >sharedpreference 如何儲存集合物件

sharedpreference 如何儲存集合物件

        public static String SceneList2String(HashMap<Integer, Boolean> hashmap)
			throws IOException {
		// 例項化一個ByteArrayOutputStream物件,用來裝載壓縮後的位元組檔案。
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 然後將得到的字元資料裝載到ObjectOutputStream
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				byteArrayOutputStream);
		// writeObject 方法負責寫入特定類的物件的狀態,以便相應的 readObject 方法可以還原它
		objectOutputStream.writeObject(hashmap);
		// 最後,用Base64.encode將位元組檔案轉換成Base64編碼儲存在String中
		String SceneListString = new String(Base64.encode(
				byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
		// 關閉objectOutputStream
		objectOutputStream.close();
		return SceneListString;
	}

	@SuppressWarnings("unchecked")
	public static HashMap<Integer, Boolean> 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);
		HashMap<Integer, Boolean> SceneList = (HashMap<Integer, Boolean>) objectInputStream
				.readObject();
		objectInputStream.close();
		return SceneList;
	}

	public static boolean putHashMap(Context context, String key,
			HashMap<Integer, Boolean> hashmap) {
		SharedPreferences settings = context.getSharedPreferences(
				PREFERENCE_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		try {
			String liststr = SceneList2String(hashmap);
			editor.putString(key, liststr);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return editor.commit();
	}

	public static HashMap<Integer, Boolean> getHashMap(Context context,
			String key) {
		SharedPreferences settings = context.getSharedPreferences(
				PREFERENCE_NAME, Context.MODE_PRIVATE);
		String liststr = settings.getString(key, "");
		try {
			return String2SceneList(liststr);
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
以上方法做的轉換,putHashMap() 是儲存物件的,,getHashMap()是獲取集合物件。