Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting null ints from sqlite in android

Tags:

android

sqlite

I have an issue that may in fact be a design issue but I am struggling to find a way around it.

In my sqlite database in my android application, I have a table called Customer. This has around 40 columns of various string and int data types. In practice, any of these columns may or may not be null.

In my code, I have a function simply called getCustomer(), which queries the database for a specific customer, and places all their cells from the database into a Customer class, which contains variables for each column. I can then pass that customer object around as I wish. The getCustomer() function returns this Customer object.

My problem is integers which may be null. I am familiar with how int cannot be null in java, but how Integer can be null. But my problem actually lies in the fact that the cells in the database can be empty (eg null).

For string columns, I simply do this:

Customer cust = new Customer();
cust.firstName = cursor.getString(0);

If cursor.getString(0); returns a null value, then the firstName variable is assigned null. Nice and simple. However with an int:

Customer cust = new Customer();
cust.daysSinceJoining = cursor.getInt(5);

The above crashes at run-time if daysSinceJoining is null. So I tried the following:

Customer cust = new Customer();
if (cursor.getInt(5) != null)
    cust.daysSinceJoining = cursor.getInt(5);

However this gives me a compiler error, as you cannot use an int in a null comparison like that.

How can I get around this problem? How can I retrieve an int from an sqlite database when the int value could be null?

like image 738
Mike Baxter Avatar asked Aug 05 '13 08:08

Mike Baxter


2 Answers

@sanders is right about the isNull() method and here's how you edit your code to use it:

Customer cust = new Customer();
if (!cursor.isNull(5))
    cust.daysSinceJoining = cursor.getInt(5);
like image 150
laalto Avatar answered Nov 18 '22 07:11

laalto


You could try the isNull() function.

like image 12
sanders Avatar answered Nov 18 '22 06:11

sanders