This is my code, it always falls into the else even when I know that the value going in (via debugger) is empty.
name = cursor.getString(curs开发者_如何学运维or.getColumnIndex("Genus")) + " " + cursor.getString(cursor.getColumnIndex("Species"));
if(name != "" && name != null)
tv.setText(name);
else
tv.setText("Error");
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");
I know it is an old Question, still contributing so as to have an alternative solution
The below mentioned solution will work if you are inserting ""
in ur row while updating it or inserting a new record for a empty field.
if(name.length() > 0 )
tv.setText(name);
else
tv.setText("Error");
The below mentioned solution will work if you are inserting null
in ur row while updating it or inserting a new record for a empty field (say edittext).
or if row with no record is created in database already..
if(name != null )
tv.setText(name);
else
tv.setText("Error");
database take the empty cell as null
if itz not manually updated later on by inserting ""
or some string value.
Both worked for me.
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
精彩评论