在SharedPrefrence中保存读取对象
private static SharedPreferences mSharedPreferences;
/** * 将对象储存到sharepreference * * @param key * @param device * @param <T> */ public static <T> boolean saveDeviceData(String key, T device) { if (mSharedPreferences == null) { mSharedPreferences = UiUtils.getContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { //Device为自定义类 // 创建对象输出流,并封装字节流 ObjectOutputStream oos = new ObjectOutputStream(baos); // 将对象写入字节流 oos.writeObject(device); // 将字节流编码成base64的字符串 String oAuth_Base64 = new String(Base64.encode(baos .toByteArray(), Base64.DEFAULT)); mSharedPreferences.edit().putString(key, oAuth_Base64).commit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 将对象从shareprerence中取出来 * * @param key * @param <T> * @return */ public static <T> T getDeviceData(String key) { if (mSharedPreferences == null) { mSharedPreferences = UiUtils.getContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); } T device = null; String productBase64 = mSharedPreferences.getString(key, null); if (productBase64 == null) { return null; } // 读取字节 byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT); // 封装到字节流 ByteArrayInputStream bais = new ByteArrayInputStream(base64); try { // 再次封装 ObjectInputStream bis = new ObjectInputStream(bais); // 读取对象 device = (T) bis.readObject(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return device; }
sharedPrefrence保存读取对象
最新推荐文章于 2023-08-28 19:18:55 发布
本文介绍了如何使用SharedPreference在Android中保存和读取自定义对象。通过将对象序列化为Base64字符串进行存储,然后反序列化回原始对象。
摘要由CSDN通过智能技术生成