1

I have this code:

Node main_node = document.getDocumentElement();
NodeList main_node_list = main_node.getChildNodes();
for( int main_iterator = 0; main_iterator < main_node_list.getLength(); main_iterator++ ) {
    Node child_node = main_node_list.item( main_iterator );
    String child_node_name = child_node.getNodeName();
    if( child_node_name == "#text" ) continue;
    Toast.makeText( context, "\"" + child_node_name + "\"", Toast.LENGTH_SHORT ).show();
    if( child_node_name == "library_visual_scenes" ) {
    ...
    }
}

It can't be any clearer, but in the Toast between the two if statements, it shows that child_node_name is exactly equal "library_visual_scenes" at some point. This without the second if statement being true.

The first if statement, when child_node_name is equal "#text" does get executed. Meaning I never see the text "#text" in the Toast.

child_node_name is a String object. Is this the correct way to compare a String with a character string?

I cannot find out what's going on here. Could this be some Android specific thing, as nearly the same code works if I run it as plain Java on my computer?

Konstantin Burov
  • 68,980
  • 16
  • 115
  • 93
Espen
  • 3,607
  • 11
  • 48
  • 75

2 Answers2

7

Replace

child_node_name == "library_visual_scenes"
child_node_name == "#text"

With

"library_visual_scenes".equals(child_node_name);
"#text".equals(child_node_name);

That is how you must compare Strings in java. "==" compares references, not contents.

Konstantin Burov
  • 68,980
  • 16
  • 115
  • 93
  • 2
    If this isn't the most common novice java programmer mistake, it has to be close. – robert_x44 Nov 27 '10 at 16:16
  • 1
    Thanx! I see you use "text".equals(String) and not String.equals("text"). Is there a prefered way? – Espen Nov 27 '10 at 16:29
  • 3
    @Espen well, "text".equals(some_variable) can save you (prevent possible NullPointerEception) in situation when some_variable is null. So I think that is preferred way in case your are not totally sure that it is safe to invoke some_variabe.equals() – Konstantin Burov Nov 27 '10 at 16:33
  • 1
    @Espen More about `"text".equals()` here http://stackoverflow.com/questions/3240854/java-xx-equalsvariable-better-than-variable-equalsxx-true – Ishtar Nov 27 '10 at 17:12
2

Change the following lines to use the equals method:

if( child_node_name.equals("#text") ) continue;

and

if( child_node_name.equals("library_visual_scenes") ) {
adamk
  • 45,184
  • 7
  • 50
  • 57