一种轻量级接收存储数据。
是以键值对的方式永久存储;
读取,写入的关联是由getSharedPreferences()中的第一个参数决定
数据的写入:
SharedPreferences msPreferences = getContext().getSharedPreferences(
"com.scxh.meituan.ui.PREFERENCES_FILE_KEY", 0);//第一个参数一般是由包名+PREFERENCES_FILE_KEY组成
SharedPreferences.Editor editor = msPreferences.edit();
editor.putString("user", "user001");
editor.putString("password", "password112");
editor.commit();
数据的读取
SharedPreferences mshaPreferences = getContext().getSharedPreferences(
"com.scxh.meituan.ui.PREFERENCES_FILE_KEY", 0);
String user = mshaPreferences.getString("user", "");
String pass =mshaPreferences.getString("password", "");:
用的单例模式自定义SharedPreferencesHelper
<span style="font-size:12px;">public class SharedPrefrenceHelper { Context context; private static SharedPrefrenceHelper sHelper; private SharedPreferences mSharedPreference; private static final String NAME = "com.scxh.android.store.PREFERENCES_FILE_KEY"; public static SharedPrefrenceHelper getInstance(Context context) { if (sHelper == null) { sHelper = new SharedPrefrenceHelper(context); } return sHelper; } private SharedPrefrenceHelper(Context context) { mSharedPreference = context.getSharedPreferences(NAME, 0); } } </span>添加对象
private static final String ID = "id";
private static final String NAME = "name";
private static final String AGE = "age";
private static final String SCORE = "score";
public void addStudent(Student student) {
Editor editor = mSharedPreferences.edit();
editor.putInt(ID, student.getId());
editor.putString(NAME, student.getName());
editor.putInt(AGE, student.getAge());
editor.putString(SCORE, student.getScore());
editor.commit();
}