1.对象的序列化与反序列化:
1)写入数据:
SharedPreferences msharedPreferences = getSharedPreferences("anthony", Context.MODE_PRIVATE);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(Data);
String sBase64 = new String(Base64.encode(baos.toByteArray(),0));
SharedPreferences.Editor editor = msharedPreferences.edit();
editor.putString("anthonyData", sBase64);
editor.commit();
} catch (IOException e) {
e.printStackTrace();
}
2)读取数据:
SharedPreferences msharedPreferences = getSharedPreferences("anthony", Context.MODE_PRIVATE);
Data data = new Data();
try {
String personBase64 = msharedPreferences.getString("anthonyData", "");
byte[] base64Bytes = Base64.decode(personBase64.getBytes(),0);
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
data = (Data) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
2.通俗做法:
SharedPreferences msharedPreferences = getSharedPreferences("anthony", MODE_PRIVATE);
//存入数据
Editor editor = msharedPreferences .edit();
editor.putString("1", "string");
editor.putInt("2", 0);
editor.putBoolean("3", true);
editor.commit();
//接收数据
Log.d("anthony", sp.getString("1", "null"));
Log.d("anthony", sp.getString("nothing", "null")); // 如果nothing不存在,则返回值为"none"