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(); }}对于需要存储的任何信息,只需重复这些get和set方法即可。
要从活动中访问它们,您可以执行以下操作:
String username = KeyValueDB.getUsername(this);
其中“ this”是对活动的引用。在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方法,则返回该值。在这种情况下不太有用,但是当您开始使用Integers和Boolean值时,这对于确保鲁棒性非常有用。



