SharePreferences是安卓平台上的一个轻量级存储类,用来存储少量数据时简单、便捷(如记住密码)。
SharePreferences以键值对形式存储数据。
SharePreferences的存储位置在/data/data/<包名>/sharedprefs目录下
SharePreferences保存数据以XML存储
下面代码是一个简单的封装,方便使用以计数功能为例,使用方法如下:
1.取值:
int count = SharePreferencesHelper.getInstance(MainActivity.this).getInt(
SharePreferencesHelper.COUNT, 0);
2.存值:
SharePreferencesHelper.getInstance(MainActivity.this).putInt(
SharePreferencesHelper.COUNT, count);
public class SharePreferencesHelper {
private static final String TAG = "SharePreferencesHelper";
//sp文件的名字
private static final String SP_NAME = "name";
//记录次数
public static final String COUNT="count";
private SharedPreferences mPreferences;
private SharedPreferences.Editor mEditor;
private static SharePreferencesHelper mSPHelper;
private Context context;
public static SharePreferencesHelper getInstance(Context context) {
if (mSPHelper == null)
synchronized (SharePreferencesHelper.class) {
if (mSPHelper == null) {
mSPHelper = new SharePreferencesHelper(context);
}
}
return mSPHelper;
}
private SharePreferencesHelper(Context context) {
this.context = context;
mPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_APPEND);
}
public boolean putString(String key, String value) {
mEditor = mPreferences.edit();
mEditor.putString(key, value);
return mEditor.commit();
}
public String getString(String key) {
return mPreferences.getString(key, "");
}
public String getString(String key, String defValue) {
return mPreferences.getString(key, defValue);
}
public boolean removeString(String key) {
mEditor = mPreferences.edit();
mEditor.remove(key);
return mEditor.commit();
}
public boolean putInt(String key, int value) {
mEditor = mPreferences.edit();
mEditor.putInt(key, value);
return mEditor.commit();
}
public int getInt(String key) {
return mPreferences.getInt(key, 0);
}
public int getInt(String key, int defValue) {
return mPreferences.getInt(key, defValue);
}
public boolean putLong(String key, long value) {
mEditor = mPreferences.edit();
mEditor.putLong(key, value);
return mEditor.commit();
}
public long getLong(String key) {
return mPreferences.getLong(key, 0);
}
public long getLong(String key, long defValue) {
return mPreferences.getLong(key, defValue);
}
public boolean putBoolean(String key, boolean value) {
mEditor = mPreferences.edit();
mEditor.putBoolean(key, value);
return mEditor.commit();
}
public boolean getBoolean(String key) {
return mPreferences.getBoolean(key, false);
}
public boolean getBoolean(String key, boolean defValue) {
return mPreferences.getBoolean(key, defValue);
}
public void clearData() {
mPreferences = context.getSharedPreferences(SharePreferencesHelper.SP_NAME, 0);
mPreferences.edit().clear().commit();
}
}