Java 尝试在 Android Studio 中实现 getSharedPreferences 时出现“无法解析方法”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23351904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:08:18  来源:igfitidea点击:

Getting "cannot resolve method" error when trying to implement getSharedPreferences in Android Studio

javaandroidsharedpreferences

提问by Scott

I'm trying to create a class KeyValueDB which stores methods for interacting with SharedPreferences, however I'm running into a problem just defining the class. All I want the constructor to do is store a sharedPreferences object with the correct filename, but I'm getting a "cannot resolve method 'getSharedPreferences(java.lang.String,int)'

我正在尝试创建一个 KeyValueDB 类,它存储与 SharedPreferences 交互的方法,但是我在定义类时遇到了问题。我想让构造函数做的就是用正确的文件名存储一个 sharedPreferences 对象,但我得到一个“无法解析方法'getSharedPreferences(java.lang.String,int)'

I am passing a String and an int... I'm not sure what I'm doing wrong. Appreciate any help!

我正在传递一个字符串和一个整数...我不确定我做错了什么。感谢任何帮助!

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);
    }

采纳答案by MattBoothDev

getSharedPreferences() needs a context to be accessed.

getSharedPreferences() 需要访问上下文。

For instance:

例如:

mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

You need to either pass the context into the constructor for KeyValueDB, or a better way would be to access that statically.

您需要将上下文传递给 KeyValueDB 的构造函数,或者更好的方法是静态访问它。

I would do this

我会这样做

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();
    }
}

Just repeat those get and set methods for any information you need to store.

只需为您需要存储的任何信息重复这些 get 和 set 方法。

To access them from an Activity, you would do this:

要从 Activity 访问它们,您可以这样做:

String username = KeyValueDB.getUsername(this);

Where "this" is a reference to the Activity. It's also good practice to setup a context in each Activity in the onCreate() method, like:

其中“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);
}

EDIT July 2016

编辑 2016 年 7 月

in response to @RishirajPurohit below, to set a username you do very much the same thing:

为了回应下面的@RishirajPurohit,要设置一个用户名,你会做同样的事情:

KeyValueDB.setUsername(mContext, "DesiredUsername");

From there everything is done for you in the previous static class, the change is committed to the shared preferences file and persisted and ready to be retrieved by the get method.

从那里开始,在前一个静态类中为您完成了所有更改,将更改提交到共享首选项文件并持久保存并准备由 get 方法检索。

Just a note on the get method, in case anyone wonders:

只是对 get 方法的说明,以防有人想知道:

public static String getUsername(Context context) {
    return getPrefs(context).getString("username_key", "default_username");
}

"default_username" is exactly as it sounds. If that get method is called first before a username is set, that is the value that is returned. Less useful in this instance, but when you start using Integers and Boolean values this is very useful for ensuring robustness.

“default_username” 就像听起来一样。如果在设置用户名之前首先调用该 get 方法,则返回值。在这种情况下不太有用,但是当您开始使用整数和布尔值时,这对于确保稳健性非常有用。

回答by Rod_Algonquin

You should pass a context there...

你应该在那里传递一个上下文......

example of getting a string value:

获取字符串值的示例:

public static String getUserName(Context ctx)
{
    return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}

where PREF_USER_NAMEis the key and the second parameter is when it cant find the key it returns ""

PREF_USER_NAME键在哪里,第二个参数是当它找不到它返回的键时""