views:

34

answers:

2

This is my code, it always falls into the else even when I know that the value going in (via debugger) is emtpy.

name = cursor.getString(cursor.getColumnIndex("Genus")) + " " + cursor.getString(cursor.getColumnIndex("Species"));

if(name != "" && name != null)
    tv.setText(name);
else
    tv.setText("Error");
+2  A: 

When doing object comparison, you must use Object.equals(Object) method. Using == or != with Objects will only return true if both Objects reference the same thing. That is why you are falling through to the else.

name.equals("") is probably what you want to use.

Also, things would probably work best if you did something like this:

if(name != null && !"".equals(name))
  tv.setText(name);
else
  tv.setText("Error");
nicholas.hauschild
Thanks a bunch!
Cptcecil
A: 

Well Cptcecil

use try - catch error handling mechanism .. instead of if ... else.

Whenever you will try read from empty cursor ... it will throw an exception that you can catch and respond accordingly without breaking your applicaton much.

Thanks

success_anil
What exception would it throw? As-is his code would throw no exceptions. In fact, he could set `tv.setText()` to `null` or to `""` and no exception would be thrown, tv would simply be empty.
Hamy