在RecyclerView Adapter中显示sharedpreference

3

我希望你能够帮助我将上下文从Activity传递到Adapter。

我正在这样调用我的共享偏好设置:

    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);

这个需要上下文,所以我使用:getApplicationContext()

但在适配器(RecyclerView)中不起作用,有人遇到同样的问题吗?

将适配器添加到清单文件中是否可以解决问题?(只是一个建议)


这是我所做的。如果您无法在SharedPreferences中访问类"context",请执行以下操作:
  1. 通过 "Context mConext" 或 "private WeakReference<Context> mContext;" 创建适配器类的上下文。
  2. 在需要使用SharedPrefernce中的上下文的任何地方,都使用"this.mContext.get()"而不是"mContext",例如: SharedPreferences preferences = this.mContext.get().getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE);
我尝试了许多其他解决方案,但始终找不到正确的方法。
- ABHIMANGAL MS
3个回答

2
我不确定您在询问什么,但这是我能想到的解决方案。 通过构造函数传递调用活动的上下文到您的适配器中,然后使用该上下文。
Context ctx;

public YourAdapter(Context ctx){
    this.ctx = ctx;
}

现在在你的适配器中,你可以这样做

SharedPreferences pref = PreferenceManager
        .getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);

这里的问题在于提供的上下文 contextThatYouProvided,我需要在适配器内部使用它。 - Jis Maxi
通过适配器构造函数将其传递给适配器。然后在适配器中使用它。 - Ratul Bin Tazul
如何传递它到这里:public class AdapterList extends RecyclerView.Adapter<RecyclerView.ViewHolder> - Jis Maxi
构造函数应该像这样:'public AdapterList (Context ctx){ this.ctx = ctx; }' - Ratul Bin Tazul

0
在您的适配器中创建一个带有Context参数的构造函数,如下所示:
public AdapterList(Context ctx){
    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);
}

通过传递参数来创建它

    adapter = new YourAdapter(getApplicationContext());

我需要在适配器中使用上下文而不是在活动本身中使用。 - Jis Maxi
我的适配器是一个类:public class AdapterList extends RecyclerView.Adapter<RecyclerView.ViewHolder> - Jis Maxi
你在哪里创建了你的适配器?在你的适配器构造函数中放置“Context”。 - WenChao
我在一个新类中创建了适配器,并从活动中调用它。在我的情况下,如何做到这一点? - Jis Maxi

0
我建议你将偏好管理代码分离成单例类,这样你就可以在任何地方访问偏好设置,就像这样。
public class SharedPreferenceManager {
private static final SharedPreferenceManager ourInstance = new SharedPreferenceManager();

public static SharedPreferenceManager getInstance() {
    return ourInstance;
}

private SharedPreferenceManager() {
}

private SharedPreferences preferences;

public void init(Context ctx) {
    preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
}

public String getValueByKey(String key) {
    return preferences.getString(key, "");
}..other functions....}

在你的activity的onCreate()方法中调用SharedPreferenceManager.getInstance().init(this)

之后你就可以随时访问SP:SharedPreferenceManager.getInstance().getValueByKey("somekey")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接