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?
@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);
You could try the isNull()
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With