SharedPreferences
存储数据
保存数据一般分为四个步骤:
- 使用Activity类的getSharedPreferences方法获得SharedPreferences对象
- 使用SharedPreferences接口的edit获得SharedPreferences.Editor对象
- 通过SharedPreferences.Editor接口的putXXX方法保存key-value对
- 通过SharedPreferences.Editor接口的commit方法保存key-value对
读取数据
读取数据一般分为两个步骤:
- 使用Activity类的getSharedPreferences方法获得SharedPreferences对象
- 通过SharedPreferences对象的getXXX方法获取数据
总结
- 通过
Activity
类的getSharedPreferences
方法获得SharedPreferences
对象 - 如果要编辑,则使用
edit()
方法获取SharedPreferences.Editor
对象 -
get
或者put
- 修改后要提交
commit()
public static final String PREFS_NAME = "test";
private void saveUserInfo(String name){
SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = userInfo.edit();
editor.putString("username", name);
editor.putInt("age", 20);
editor.commit();//提交修改
}
private String getUserInfo(){
SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String username = userInfo.getString("username", "人间几度清明");//读取username
int age = userInfo.getInt("age", 0);//读取age
return username;
}
private void removeUserInfo(){
SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = userInfo.edit();//获取Editor
editor.remove("age");
editor.commit();
}
private void clearUserInfo(){
SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = userInfo.edit();//获取Editor
editor.clear();
editor.commit();
}