android - 在 Android 的静态类中引用非静态方法 - getSharedPref

标签 android sharedpreferences static-members

我有以下代码:

  Context context = Activity.getApplicationContext();
             SharedPreferences settings = context.getSharedPreferences("AutoMsgSharedPrefs", MODE_PRIVATE);

            // Writing data to SharedPreferences
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("key", "some value");
            editor.commit();

我一直在尝试使用 SharedPrefs 来存储在示例中的“对话”类中给出的消息 - https://developer.android.com/samples/MessagingService/index.html .但是,我得到“如果我尝试在“Conversation”类的构造函数中实现它,则无法从静态类引用非静态方法。那么我该如何解决这个问题?

如果我按照建议更新,这里是错误的屏幕截图:

enter image description here

最佳答案

这里

Context context = Activity.getApplicationContext();

此行不会为您的应用程序返回有效的上下文以调用 getSharedPreferences

要从非 Activity,Service,... 类调用 getSharedPreferences,您需要从 Activity,Service,.. 等应用程序组件传递有效上下文

要在 Conversation 中获取 Context,请使用已在给定示例中创建的 Conversation 类构造函数,您需要再添加一个参数:

Context mContext;
public Conversation(int conversationId, String participantName,
                            List<String> messages,Context mContext) {
            .....
            this.mContext=mContext;
        }

现在使用 mContextConversation 类调用 getSharedPreferences 方法:

SharedPreferences settings = mContext.getSharedPreferences("AutoMsgSharedPrefs", 
                                                           Context.MODE_PRIVATE);

关于android - 在 Android 的静态类中引用非静态方法 - getSharedPref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815037/

相关文章:

Android 共享首选项不能正确保存

c++ - 模板类可以在 C++ 中具有静态成员吗

c++ - constexpr 使用静态函数初始化静态成员

安卓 : translate the language of whole app on click

android - Android 的自定义内容提供程序? (修改记事本示例)

Android 在 Activity 之间传递对象

android - 在 onBindViewHolder 之外使用 ViewHolder 元素?

java - Android studio,这不是从共享首选项中检索字符串并将其转换为 hashset<string> 的正确方法吗?

java - 如何在 SharedPreferences 中保存 JSON 数组?

java - 静态 block 与静态方法 - 初始化静态字段