【问题标题】:Android SharedPreferences issueAndroid SharedPreferences 问题
【发布时间】:2011-09-13 12:36:07
【问题描述】:

我需要一些有关 Android 共享首选项的帮助。我正在尝试在 SP 中放置一个布尔类型,并使其在我的应用程序中的所有其他活动中都可见。我希望能够从另一个活动中将布尔类型的状态更改为真/假,以便我可以在其中进行一些更改UI 取决于该布尔值。 目前我正在使用这段代码,我理解但它不正确。

这里是:

活动一:

boolean isLoggedIn = false;

        SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = isLogged.edit();
        editor.putBoolean("isLoggedIn", isLoggedIn);
        editor.commit();

活动 2:

        boolean isLogged=true;

        int mode = Activity.MODE_PRIVATE;
        SharedPreferences  mySharedPreferences;
        mySharedPreferences=getSharedPreferences("isLoggedIn",mode);
        mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
        boolean bool = mySharedPreferences.getBoolean("isLoggedIn",false);

        Log.w("Boolean","Boolean state : "+bool);

【问题讨论】:

  • 我的解决方案不适合你吗?

标签: java android sharedpreferences


【解决方案1】:

在 Activity 2 中尝试这样使用,它会起作用

mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

并删除下面的行

mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);

【讨论】:

  • ingsaurabh 是对的。你现在有 2 个不同的偏好存储,default 和 isLoggedIn。
【解决方案2】:

edit.commit(); 放在 mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged); 之后 这将帮助您获得正确的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2021-01-03
    • 1970-01-01
    • 2023-03-19
    • 2015-05-03
    相关资源
    最近更新 更多