开发者

android: String value match another String value using operand == not working?

开发者 https://www.devze.com 2023-02-27 03:14 出处:网络
Hopefully this is an easy fix, but for the moment is is boggling me (Actionscript programmer new to Java programming).

Hopefully this is an easy fix, but for the moment is is boggling me (Actionscript programmer new to Java programming).

I have a string variable coming from getExtra that I am comparing to a static sting in an if statement:

Bundle extras = getIntent().getExtras();
dir = extras.getString("com.activity.Dir");

Then I am utilizing this in an if statement

if (dir == "content"){
    // load page content
} else {
    // load a menu
}

I am Toasting the value of dir on th开发者_运维百科e line before it and regardless of the value it will not hit the == statement; ie: if dir == "content", it hits the else; if dir == "foo", it hits the else, etc.

I tried placing dir into another String var and used .toString();

String directive = dir.toString();

That does the same thing. What am I missing here?

SOLVED: Used dir.equals("content"); // Thanks for you being patient with me SO!


You must not compare strings via ==, but via .equals()


Strings are Objects, and to do correct Object equality comparisions, you need to use

dir.equals("content");

or better yet (to avoid possible null pointer exceptions)

"content".equals(dir);


You should use equals for Strings on Java.

2 tips:

  • Add the string you know it isn't null to avoid nullpointers. Ex: "compare".equals(string)
  • Use equalsIgnoreCase() instead of equals if you wish to compare strings and ignore the case differences.


Use the equals method instead of ==


"vuqar"=="vuqar" or "vuqar"!="vuqar" not works correct

You have to use

if(vuqar.equals("vuqar")){//action}

OR

if(!"vuqar".equals("vuqar")){//action}
0

精彩评论

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