英文:
Stored variable always read as false?
问题
我在我的Java类中有这个:
public class ActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
prefs.edit().putBoolean("saved", true).apply();
}
}
而在我的Kotlin类中有这个:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.mylayout)
val prefs = getPreferences(MODE_PRIVATE)
val saved = prefs.getBoolean("saved", false)
System.out.println("Saved value: " + saved) // 总是打印false!
}
即使在我的Java类中的代码被调用时,最后一行总是打印出 false
。为什么呢?
英文:
I have this in my Java class:
public class ActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
prefs.edit().putBoolean("saved", true).apply();
}
}
And this in my Kotlin class:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.mylayout)
val prefs = getPreferences(MODE_PRIVATE)
val saved = prefs.getBoolean("saved", false)
System.out.println("Saved value: " + saved) // always prints false!
}
The last line always prints false
even when the code in my Java class is called. Why?
答案1
得分: 3
getPreferences()
会返回一个与调用它的上下文范围相关的偏好设置对象(实际上只是按类命名)。
使用 getSharedPreferences()
或 PreferenceManager.getDefaultSharedPreferences()
来获取一个在应用程序全局共享的对象。
你的 Kotlin 类当前正在使用 getPreferences()
,因此它查看的是与你通过 getSharedPreferences()
按名称获取的 Receiver 中不同的偏好设置。
英文:
getPreferences()
gives you a preferences object that is scoped to the context you called it from (actually just naming it after the class).
Use getSharedPreferences()
or PreferenceManager.getDefaultSharedPreferences()
to get an object that is shared globally in your app.
Your Kotlin class is currently using getPreferences()
so it is not looking at the same preferences you're using in your Receiver that you got by name with getSharedPreferences()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论