开发者

comparison of two Strings doesn't work in android [duplicate]

开发者 https://www.devze.com 2023-03-22 15:10 出处:网络
This question already has answers here: How do I compare str开发者_开发百科ings in Java? (23 answers)
This question already has answers here: How do I compare str开发者_开发百科ings in Java? (23 answers) Closed 10 years ago.

here's my code, Eclipse doesn't show any errors, program's working fine, but it simply doesn't do exactly what i want:)

    View image_view_danger_rate = (ImageView) findViewById(R.id.origin);
    View image_view_origin = (ImageView) findViewById(R.id.danger_rate);

    String entry_tag = (String) descriptionResultView.findViewById(resID).getTag();

    String dangerous = "dangerous";
    String not_dangerous = "not_dangerous";

    if ( entry_tag == dangerous) {
        image_view_danger_rate.setBackgroundResource(R.drawable.attention);
    }else if ( entry_tag == not_dangerous) {
        image_view_danger_rate.setBackgroundResource(R.drawable.its_ok);
        image_view_origin.setBackgroundResource(R.drawable.artificial);
    }

The application should choose between two images to pop-up on the screen, depending on a tag stored in the xml file. So, if the tag says "dangerous", then should be shown the "attention"-image. If the tag says "not_dangerous", there should be the "its_ok"-image.

Now, displaying the images without an if-comparison works perfectly.

If i print out the tags as a string, it works, it prints correctly "dangerous" or "not_dangerous", depending on the tag.

But if there's a if-comparison as shown above, nothing happens, no image is shown.

Please anyone help!!=)


Use string1.equalsIgnoreCase("something) or .equals("Something");

With == (for strings) in java you are comparing they are of same reference. Like you did is the test if both of them are strings objects.


In java, a==b is used to compare 2 references, not the objects themselves.

so if you have 2 strings that you want to compare, use the equals() method on String. for eg

boolean resultOfComparison=stringA.equals(stringB);


Use

entry_tag.equals(dangerous)

you're comparing actual String objects, not their content. In Java, operators are not overloaded so == can't be used to compare strings.


In Java, if you want to compare Strings, you need to use equals():

if (entry_tag.equals(dangerous)) {
}
0

精彩评论

暂无评论...
验证码 换一张
取 消