0

我在我的 android 应用程序中使用 sqlite 来存储数据。每次启动应用程序时,我都会从服务器获取一些数据并将其存储在客户端中。现有数据更新和新数据插入到数据库中。

但是在许多情况下,当我通过查询从 DB 访问现有项目时,我会从 DB 中得到一个空白光标 "select * from Table where itemId = x"。就好像我在更新之前从设备/模拟器中提取数据库一样,我可以看到数据存在于数据库中。

仅当我从服务器获取许多数据并与现有数据进行比较时,才会出现此问题。比较是在循环中完成的,每次我得到一个光标并在移动到下一个比较之前关闭它。

try{
int[] ids = getIds(); // get required ids
for(i =0; i<ids.length, i++)
{
// 
Cursor c = db.rawQuery("Select * from Table where id = "+ids[i]);
if(c == null || (c != null && c.getcount() == 0))
{
 // new data
}else if(c.getcount()>0)
{
// existing data
}
}
}catch(Exception e){
    e.printStackTrace();
}finally{
if(c!=null && !c.isClosed())
{
c.close()
}
c = null;
}

我注意到,第一次我得到一个带有数据的光标,但在那之后我得到了空白光标。

4

2 回答 2

1

查询后,如果游标包含多于零行,则该部分:

{
// existing data
}

will be executed "size" times. If the cursor is null or does not contains any row, your section:

{
 // new data
}

will be executed "size" times.

This is because your query is static. You are making, for each iteration in the loop, the same query. If this is what you want you should put the call to rawQuery method outside of loop.

Moreover:

if(c == null || c != null && c.getcount() == 0)

is equivalent to:

if(c == null || c.getCount() == 0)

The if condition at line:

else if(c.getcount()>0)

can be omitted.

于 2013-05-13T13:30:44.307 回答
1

The problem is resolved.

Sorry the issue was not related to the query but the input parameter (id).In some conditions id was wrong and hence it was returning blank cursor.

于 2013-05-14T09:22:39.760 回答