我有以下代码:
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”类的构造函数中实现它,则无法从静态类引用非静态方法。那么我该如何解决这个问题?
如果我按照建议更新,这里是错误的屏幕截图:
最佳答案
这里
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;
}
现在使用 mContext
从 Conversation
类调用 getSharedPreferences
方法:
SharedPreferences settings = mContext.getSharedPreferences("AutoMsgSharedPrefs",
Context.MODE_PRIVATE);
关于android - 在 Android 的静态类中引用非静态方法 - getSharedPref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815037/