Android进阶——Sharedpreferences保存对象和图片等复杂类型( 二 )


Android进阶——Sharedpreferences保存对象和图片等复杂类型

文章插图
三、保存和读取序列化的对象
由于二进制数据经过编码后可以用以字符串的形式存储,所以保存对象也成为了可能,但是这个类必须是可序列化即 (实际上接口是个空接口,只是为了标记该对象是被序列化的),然后可以通过保存再转为二进制存储 。
1、保存序列化的对象
/*** @param user*/public static void saveUser(Context context, String preferenceName,String key,User user) throws Exception {if(user instanceof Serializable) {SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceName, context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPreferences.edit();ByteArrayOutputStream baos = new ByteArrayOutputStream();try {ObjectOutputStream oos = new ObjectOutputStream(baos);oos.writeObject(user);//把对象写到流里String temp = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));editor.putString(key, temp);editor.commit();} catch (IOException e) {e.printStackTrace();}}else {throw new Exception("User must implements Serializable");}}
2、读取序列化的对象
public static User getUser(Context context, String preferenceName,String key) {SharedPreferences sharedPreferences=context.getSharedPreferences(preferenceName,context.MODE_PRIVATE);String temp = sharedPreferences.getString(key, "");ByteArrayInputStream bais =new ByteArrayInputStream(Base64.decode(temp.getBytes(), Base64.DEFAULT));User user = null;try {ObjectInputStream ois = new ObjectInputStream(bais);user = (User) ois.readObject();} catch (IOException e) {}catch(ClassNotFoundException e1) {}return user;}
当然也是可以存储各种集合类的比如说List,都可以通过转为输出流进而编码存储:
public static String listToString(List list)throws IOException {// 实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件 。ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();// 然后将得到的字符数据装载到ObjectOutputStreamObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);// writeObject 方法负责写入特定类的对象的状态,以便相应的 readObject 方法可以还原它objectOutputStream.writeObject(list);// 最后,用Base64.encode将字节文件转换成Base64编码保存在String中String listString = new String(Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT));// 关闭objectOutputStreamobjectOutputStream.close();return listString;}@SuppressWarnings("unchecked")public static List StringToList(String listString) throws StreamCorruptedException, IOException,ClassNotFoundException {byte[] mobileBytes = Base64.decode(listString.getBytes(),Base64.DEFAULT);ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(mobileBytes);ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);List WeatherList = (List) objectInputStream.readObject();objectInputStream.close();return WeatherList;}
测试代码(就是自己写的工具类):
/*** Sharedpreferences 保存复杂数据*/public class MainActivity extends Activity {@butterknife.Bind(R.id.save_list_btn)Button saveListBtn;@butterknife.Bind(R.id.save_img_btn)Button saveImgBtn;@butterknife.Bind(R.id.save_obj_btn)Button saveObjBtn;@butterknife.Bind(R.id.show_imv)ImageView showImv;@butterknife.Bind(R.id.imfo_edt)EditText imfoEdt;@butterknife.Bind(R.id.activity_main)RelativeLayout activityMain;private finalstatic String SHAREDPREFS_USER="user_config";private finalstatic String USER_AVATAR="avatar";private static final String USER_IMFO = "user";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);butterknife.ButterKnife.bind(this);}@TargetApi(Build.VERSION_CODES.JELLY_BEAN)@OnClick({R.id.save_img_btn,R.id.save_list_btn,R.id.save_obj_btn})void OnClick(View v){switch (v.getId()){case R.id.save_img_btn:if("read Image".equals(saveImgBtn.getText())) {Drawable drawable=SharedpreferesUtil.getDrawableByKey(this, SHAREDPREFS_USER, USER_AVATAR);showImv.setVisibility(View.VISIBLE);//showImv.setBackgroundResource(R.mipmap.ic_launcher);showImv.setImageBitmap(IOUtil.drawableToBitmap(drawable));}else {SharedpreferesUtil.saveDrawable(this, SHAREDPREFS_USER, R.mipmap.ic_launcher, USER_AVATAR);saveImgBtn.setText("read Image");}break;case R.id.save_list_btn:break;case R.id.save_obj_btn:if("read object".equals(saveObjBtn.getText())) {showImv.setVisibility(View.GONE);User user=SharedpreferesUtil.getUser(this,SHAREDPREFS_USER,USER_IMFO);imfoEdt.setVisibility(View.VISIBLE);imfoEdt.setText("Id:"+user.get_id()+"Name:"+user.getName());}else {try {SharedpreferesUtil.saveUser(this, SHAREDPREFS_USER, USER_IMFO, new User(1001, "CrazyMo"));saveObjBtn.setText("read object");} catch (Exception e) {e.printStackTrace();}}break;default:break;}}}