1.存储<对象> 类型
@SuppressWarnings("unchecked")
public boolean setObject(String key, T object) {
if(sharedPreference == null){
packageName = context.getPackageName() + "_preferences";
sharedPreference = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
}
//创建字节输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//创建字节对象输出流
ObjectOutputStream out = null;
try {
//然后通过将字对象进行64转码,写入key值为key的sp中
out = new ObjectOutputStream(baos);
out.writeObject(object);
String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
Editor editor = sharedPreference.edit();
editor.putString(key, objectVal);
editor.commit();
return true;
} catch (IOException e) {
e.printStackTrace();
return false; } }
2.获取<对象>类型
publicT getObject(String key) {
if(sharedPreference == null){
packageName = context.getPackageName() + "_preferences";
sharedPreference = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
}
T device = null;
if (sharedPreference.contains(key)) {
String string = sharedPreference.getString(key, "");
if (TextUtils.isEmpty(string)) {
return null;
} else {
//将16进制的数据转为数组,准备反序列化
byte[] stringToBytes = Base64.decode(string.getBytes(), Base64.DEFAULT);
ByteArrayInputStream bis = new ByteArrayInputStream(stringToBytes);
ObjectInputStream is = null;
try {
is = new ObjectInputStream(bis);
//返回反序列化得到的对象
device = (T) is.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return device;
}
3.前方高能!!!注意:
需要存储的对象必须实现Serializable,同时
这个对象的子类也必须实现Serializable,不然都会报java.io.NotSerializableException!!!
转载请注明出处 shareprefrence存储和获取对象(java.io.NotSerializableEx... - 简书
网友评论