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

☆樱花仙子☆ 提交于 2019-12-25 11:47:13

问题


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.


回答1:


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



回答2:


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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/25791518/compare-two-strings-with-equals-dont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!