0

I am using sqlite in my android application to store data. Each time when i start the application i get some data from server and store it in client.The existing data updates and new data inserts into the db.

But in many case i get a blank cursor from DB when i access an existing item from DB by querying "select * from Table where itemId = x". where as if i extract the db from device/emulator before updating it, i can see the data exist in the db.

This problem happen only if i get many data from server and compare with the existing data. The comparison is done in a loop and each time i get a cursor and close it before moving to next comparison.

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;
}

I noticed, for the 1st time i get a cursor with data but after that i get blank cursor.

4
  • 3
    You need to post code to get help on this one. May 13, 2013 at 6:13
  • Remove the catch to get error messages.
    – CL.
    May 13, 2013 at 12:01
  • There is no exception, i am geting an empty cursor.
    – Atmaram
    May 13, 2013 at 12:52
  • I can't understand your code! Why you are getting the same cursor "size" times?
    – GVillani82
    May 13, 2013 at 13:12

2 Answers 2

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.

1

After the query, if the cursor contains more than zero rows, the section:

{
// 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.

2
  • Thanks for your response. I am not executing the same query size times rather the x value is just for reference, i should have used "i" instead. Consider its same query with different parameter in each loop.
    – Atmaram
    May 13, 2013 at 14:26
  • Maybe, when you make the query for i==1, no result is found.
    – GVillani82
    May 13, 2013 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.