SharedPreferences 以 key-value键值对的形式保存数据,不需要指定文件后缀名,后缀自动设置为 *.xml,如下例的 config,最终为 config.xml
一、保存数据
//存数据
public static boolean saveUserInfo(Context context, String username, String password){
SharedPreferences sharedPrefs = context.getSharedPreferences("config", Context.MODE_PRIVATE);
Editor editor = sharedPrefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
return true;
}
注:只有执行 commit()方法后,才将数据保存。
二、读取数据:
//取数据
public static Map<String,String> getSavedUserInfo(Context context){
SharedPreferences shared = context.getSharedPreferences("config", Context.MODE_PRIVATE);
String username = shared.getString("username", "");
String password = shared.getString("password", "");
Map<String,String> map = new HashMap<String, String>();
map.put("username", username);
map.put("password", password);
return map;
}