sharedpreference 如何存储集合对象

转自:http://m.blog.csdn.net/blog/xiabing082/9792271


使用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()是获取集合对象。 
其他不做过多介绍,方便大家拿过来直接使用即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值