0

i would like to create a sharedpreferences for boolean value check, but the value always return false. How to return the correct boolean value for sharedpreferences?

Below is my code

  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

}

Here is the code to get sharedpreferences value

 @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));
         } 
Cœur
  • 37,241
  • 25
  • 195
  • 267
michelletbs
  • 809
  • 2
  • 9
  • 19

3 Answers3

1

You are comparing two String variables with == operator instead use .equals() method.

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

it will work.

Refer This Question for == and equals().

Community
  • 1
  • 1
ELITE
  • 5,815
  • 3
  • 19
  • 29
0

use

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

instead of

if(favUrl == text) {
    switchState=true;
}
David Yee
  • 3,515
  • 25
  • 45
Anup Dasari
  • 488
  • 1
  • 4
  • 13
0

You can simplify your code to:

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
}
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87