Tutorial :How can I check if a string I have returned from a cursor is empty or null in an Android cursor?



Question:

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(cursor.getColumnIndex("Genus")) + " " + cursor.getString(cursor.getColumnIndex("Species"));    if(name != "" && name != null)      tv.setText(name);  else      tv.setText("Error");  


Solution:1

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");  


Solution:2

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.


Solution:3

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »