使用SharedPreferences保存对象
我们知道,SP可以保存像String和int这样的简单类型的数据,但不能直接保存对象。在需要保存对象的时候,就需要用到格式转换。
步骤:
1、将复杂数据(obj)转换为字节码;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(obj);
2、然后将字节码按Base64编码格式转换为String;
String bytesToHexString = new String(Base64.encode(bos.toByteArray(), Base64.DEFAULT));
3、
SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString(key, string);
editor.commit();
保存String;
注意,这段代码应该放到具体的调用方法中,不能作为全局的。SharedPreferences 是进行一个读写文件的操作,会出现无响应的情况。
4、使用时,拿到String数据
String string = sharedPreferences.getString(key, "");
5、将string按Base64解码格式转换字节码
byte[] stringToBytes = Base64.decode(string, Base64.DEFAULT);
6、将字节码转换为原始数据
ByteArrayInputStream bis=new ByteArrayInputStream(stringToBytes);
ObjectInputStream is = new ObjectInputStream(bis);
Obj obj = (obj)is.readObject();
以上,1~3是保存的操作,4~6是取出的操作。
另外,需要保存的对象需要使用Serializable接口进行实例化,否则会报NotSerializableException的异常