从android中的sqlite获取null int

Mik*_*ter 5 sqlite android

我有一个问题,实际上可能是一个设计问题,但我正在努力找到解决方法.

在我的android应用程序的sqlite数据库中,我有一个名为的表Customer.这有大约40列各种字符串和int数据类型.实际上,这些列中的任何一列都可能为空,也可能不为空.

在我的代码中,我有一个简单调用的函数getCustomer(),它查询数据库中的特定客户,并将数据库中的所有单元格放入一个Customer类中,该类包含每列的变量.然后,我可以按照自己的意愿传递该客户对象.该getCustomer()函数返回此Customer对象.

我的问题是整数,可能是null.我熟悉如何int在java中不能为null,但如何Integer可以为null.但我的问题实际上在于数据库中的单元格可以为空(例如null).

对于字符串列,我只是这样做:

Customer cust = new Customer();
cust.firstName = cursor.getString(0);
Run Code Online (Sandbox Code Playgroud)

如果cursor.getString(0);返回null值,则将firstName变量赋值为null.很好,很简单.但是使用int:

Customer cust = new Customer();
cust.daysSinceJoining = cursor.getInt(5);
Run Code Online (Sandbox Code Playgroud)

如果daysSinceJoining为null,则上面在运行时崩溃.所以我尝试了以下方法:

Customer cust = new Customer();
if (cursor.getInt(5) != null)
    cust.daysSinceJoining = cursor.getInt(5);
Run Code Online (Sandbox Code Playgroud)

但是,这给了我一个编译器错误,因为你不能int在这样的null比较中使用.

我怎样才能解决这个问题?我怎样才能从SQLite数据库检索一个int当int值可能为空?

laa*_*lto 11

@sanders对isNull()方法是正确的,以下是编辑代码以使用它的方法:

Customer cust = new Customer();
if (!cursor.isNull(5))
    cust.daysSinceJoining = cursor.getInt(5);
Run Code Online (Sandbox Code Playgroud)


san*_*ers 10

你可以试试这个isNull()功能.


Ste*_*ike 5

请看看答案:

getInt null-constraints

我认为这应该适合你:

int lIndex = cursor.getColumnIndexOrThrow(COLUMN);
Integer lInteger = null;
if (!cursor.isNull(lIndex)
lInteger = cursor.getInt(lIndex);
Run Code Online (Sandbox Code Playgroud)