存储的变量始终被读取为 false?

huangapple go评论74阅读模式
英文:

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().

huangapple
  • 本文由 发表于 2020年10月10日 22:12:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64294353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定