0

我想为布尔值检查创建一个共享首选项,但该值始终返回 false。如何为 sharedpreferences 返回正确的布尔值?

下面是我的代码

  public boolean getBtnState(Context context,String text)//edit to store url here and check the boolean here
{
    SharedPreferences prefs;
    prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

    String favUrl = getPrefsFavUrl(context);

    boolean switchState = false;

    if(favUrl == text) {
        switchState=true;
    }

    return switchState;//always return false here

}

这是获取 sharedpreferences 值的代码

 @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        showProgress();
        imageView = (ImageView) findViewById(R.id.btn_favourite);

        Boolean stateBtnNow=sharedPreference.getBtnState(context,mUrl);
         if(stateBtnNow) {
             imageView.setColorFilter(Color.argb(255, 249, 0, 0));//red
         }
        else
         {
             imageView.setColorFilter(Color.argb(255, 192, 192, 192));
         } 
4

3 回答 3

1

您正在将两个String变量与==运算符进行比较,而不是使用.equals()方法。

if(favUrl.equals(text)) {
    switchState=true;
}

它会起作用的。

参考这个==问题和equals()

于 2016-01-29T07:54:41.700 回答
0

利用

if(favUrl.equals(text)){
    switchState = true;
}

代替

if(favUrl == text) {
    switchState=true;
}
于 2016-01-29T07:54:17.213 回答
0

您可以将代码简化为:

public boolean getBtnState(Context context,String text) { //edit to store url here and check the boolean here
    SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    return getPrefsFavUrl(context).equals(text); // fixed and simplified code
}
于 2016-01-29T08:06:35.847 回答