Kroenig
Kroenig

Reputation: 684

compare two strings with .equals() don't work

I get a string form a list and try to compare it with some strings in the values and then do some stuff

for(int i=0; i<sizeOfList; i++){

    String LIST_TITLE;

    LIST_TITLE = list_title.get(i); //the List list_title includes some strings

    if(LIST_TITLE.equals(R.string.percentbattery)) {
        //do stuff
        Log.d("EQUAL!","" + LIST_TITLE);
    } else if(LIST_TITLE.equals(R.string.screenrecorder) == true) {
        //do stuff
        Log.d("EQUAL!","" + LIST_TITLE);
    } else if(LIST_TITLE.equals(R.string.eightsms) == true) {
        //do stuff
        Log.d("EQUAL!","" + LIST_TITLE);
    } else {
        // do stuff
        Log.e("TITLE NOT EQUAL","" + LIST_TITLE);
    }
}

If I compare my LIST_TITLE with the (R.string. ...) in my Logcat they are equal, but I get only the "TITLE NOT EQUAL" Log from the else statement.

Is there another way to compare these strings? the "==" method also don't work.

Upvotes: 0

Views: 706

Answers (4)

Alexander Zhak
Alexander Zhak

Reputation: 9272

LIST_TITLE.equals(R.string.percentbattery)

This is incorrect, because you're trying to compare string with resource ID You should get the string from resource first:

LIST_TITLE.equals(getResources().getString(R.string.percentbattery))

Upvotes: 2

cliffroot
cliffroot

Reputation: 1691

R.string.some_id is just an integer by which you can get the String from the resources. So in order to compare Strings correctly in you case you have to do:

String precentBattery = getResources().getString(R.string.percentbattery);
if (LIST_TITLE.equals (percentBattery)) ...

Upvotes: 0

codeMagic
codeMagic

Reputation: 44571

R.string.xxx is an int. You need to get the String from that res

Something like

if(LIST_TITLE.equals(getResources().getString(R.string.percentbattery)))

This is assuming you have Activity Context available. Otherwise, you would need to add a Context variable in front of getResources()

Upvotes: 0

Budius
Budius

Reputation: 39836

R.string.percentbattery is not a String, it's an Integer that is the ID to reference the string.

what u want is:

LIST_TITLE.equals(context.getResources.getString(R.string.percentbattery))

Upvotes: 3

Related Questions