1. 存
SharedPreferences mSharedPreferences = getSharedPreferences("存在本地的文件名", MODE_PRIVATE);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(key1, value1);
editor.putString(key2, value2);
editor.putString(key3, null);
editor.commit();
2. 取
SharedPreferences mSharedPreferences = getSharedPreferences("存在本地的文件名", MODE_PRIVATE);
String value1 = mSharedPreferences.getString(key1);
3. 把对象存入本地,要用到 commons-codec-1.10.jar,对象可以是List
public void saveObject(Object object) {
SharedPreferences preferences = getSharedPreferences("存在本地的文件名", MODE_PRIVATE);
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
String objectBase64 = new String(Base64.encodeBase64(baos.toByteArray()));
SharedPreferences.Editor editor = preferences.edit();
editor.putString("该对象存在本地的名字", objectBase64);
editor.commit();
} catch(IOException e) {
e.printStackTrace();
} finally {
if(baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4. 从本地中读取对象
@SuppressWarnings("unchecked")
public Object getObject() {
List<自定义对象> list = null;
SharedPreferences preferences = getSharedPreferences("存在本地的文件名", MODE_PRIVATE);
String objectBase64 = preferences.getString("该对象在本地的名字", "");
byte[] base64 = Base64.decodeBase64(objectBase64.getBytes());
ByteArrayInputStream bais = null;
ObjectInputStream bis = null;
try {
bais = new ByteArrayInputStream(base64);
bis = new ObjectInputStream(bais);
try {
list = (List<自定义对象>) bis.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bais != null) {
try {
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}