80,351
社区成员
发帖
与我相关
我的任务
分享
// 上面的构造方法调这个构造方法
private Context context;
private SharedPreferences sp = null;
private Editor edit = null;
public SharedPreferencesUtil(Context context, SharedPreferences sp) {
this.context = context;
this.sp = sp;
edit = sp.edit();
}
// 构造方法
public SharedPreferencesUtil(Context context, String filename) {
this(context, context.getSharedPreferences(filename,
Context.MODE_PRIVATE));
}
// 设置值
public void setValue(String key, String value) {
edit.putString(key, value);
edit.commit();
}
// 获取值
public String getValue(String key, String defaultValue) {
return sp.getString(key, defaultValue);
}
// 实现
private SharedPreferencesUtil mSharedPreferencesUtil;
mSharedPreferencesUtil = new SharedPreferencesUtil(this, "user");
// 获取账号密码
String account = mSharedPreferencesUtil.getValue("account", "");
String pwd = mSharedPreferencesUtil.getValue("pwd", "");
// 设置账号密码
mSharedPreferencesUtil.setValue("account",account);
mSharedPreferencesUtil.setValue("pwd", pwd);