我正在尝试创建一个类 KeyValueDB,它存储用于与 SharedPreferences 交互的方法,但是我在定义类时遇到了问题。我想让构造函数做的就是用正确的文件名存储一个 sharedPreferences 对象,但我得到一个“无法解析方法‘getSharedPreferences(java.lang.String,int)’”
我正在传递一个字符串和一个整数...我不确定我做错了什么。感谢任何帮助!
package com.farmsoft.lunchguru.utils;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
/**
* Created by sxs on 4/28/2014.
*/
public class KeyValueDB {
private SharedPreferences sharedPreferences;
public KeyValueDB(String prefName) {
sharedPreferences = getSharedPreferences(prefName, Context.MODE_PRIVATE);
}
最佳答案
getSharedPreferences() 需要访问上下文。
例如:
mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
您需要将上下文传递给 KeyValueDB 的构造函数,或者更好的方法是静态访问它。
我会这样做
public class KeyValueDB {
private SharedPreferences sharedPreferences;
private static String PREF_NAME = "prefs";
public KeyValueDB() {
// Blank
}
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static String getUsername(Context context) {
return getPrefs(context).getString("username_key", "default_username");
}
public static void setUsername(Context context, String input) {
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString("username_key", input);
editor.commit();
}
}
只需为您需要存储的任何信息重复这些获取和设置方法即可。
要从 Activity 访问它们,您可以这样做:
String username = KeyValueDB.getUsername(this);
其中“this”是对 Activity 的引用。在 onCreate() 方法中为每个 Activity 设置一个上下文也是一种很好的做法,例如:
public class myActivity extends Activity{
Context mContext;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
String username = KeyValueDB.getUsername(mContext);
}
编辑 2016 年 7 月
作为对下面@RishirajPurohit 的回应,要设置用户名,您需要做很多相同的事情:
KeyValueDB.setUsername(mContext, "DesiredUsername");
在之前的静态类中,一切都已为您完成,更改已提交到共享首选项文件并持久保存并准备好通过 get 方法检索。
只是对 get 方法的注释,以防万一有人想知道:
public static String getUsername(Context context) {
return getPrefs(context).getString("username_key", "default_username");
}
“default_username”顾名思义。如果在设置用户名之前首先调用该 get 方法,则返回该值。在这种情况下用处不大,但是当您开始使用整数和 boolean 值时,这对于确保稳健性非常有用。
关于java - 尝试在 Android Studio 中实现 getSharedPreferences 时出现 "cannot resolve method"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23351904/