1、保存到本地
/** * 保存复杂类型的数据 * @param context 上下文 * @param obj 要保存的对象 * @param key 对象在本地对应的key * @author yangq-c */ public static void saveComplexDataBySP(Context context, Object obj, String key) { SharedPreferences passwd = ((Activity) context) .getPreferences(context.MODE_PRIVATE); SharedPreferences.Editor editor = passwd.edit(); ByteArrayOutputStream toByte = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(toByte); } catch (IOException e) { Log.e(TAG, e.toString()); } if (oos != null) { try { oos.writeObject(obj); } catch (IOException e) { Log.e(TAG, e.toString()); } } else { Log.e(TAG, "oos == null"); } // 对byte[]进行Base64编码 String complexDataBase64 = new String(Base64.encodeToString( toByte.toByteArray(), Base64.NO_WRAP)); editor.putString(key, complexDataBase64); editor.commit(); }2、从本地取值
/** * 获取复杂类型的数据 * @param context 上下文 * @param key 对象在本地对应的key * @return * @author yangq-c */ public static Object getComplexDataBySP(Context context, String key) { Object objRes = null; SharedPreferences prefer = ((Activity) context) .getPreferences(context.MODE_PRIVATE); String passwordinbase64 = prefer.getString(key, null); if (passwordinbase64 != null) { byte[] base64Bytes = Base64.decode(passwordinbase64, Base64.NO_WRAP); ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes); ObjectInputStream ois = null; try { ois = new ObjectInputStream(bais); } catch (StreamCorruptedException e) { Log.e("------", e.toString()); } catch (IOException e) { Log.e("------", e.toString()); } if (ois != null) { try { objRes = (Object) ois.readObject(); } catch (OptionalDataException e) { Log.e("------", e.toString()); } catch (ClassNotFoundException e) { Log.e("------", e.toString()); } catch (IOException e) { Log.e("------", e.toString()); } } } return objRes; }