Skip to content Skip to sidebar Skip to footer

How Can An Android Cursor Be At A Negative Position?

While learning to iterate over a cursor, I learned that I needed to first move to position '-1' and then use 'moveToNext' in a loop: cursor.moveToPosition(-1); for (int i = 0; cur

Solution 1:

A cursor should not be at a negative position, a cursors data starts at position 0 which is why you always need to move the cursor to the first position before getting the data using

if(cursor.moveToFirst()){
    //you have data in the cursor
}

now to go through the cursor just simply use a do/while loop

do{
    //process cursor data
}while(cursor.moveToNext);

what you are doing with your for loop breaks that convention, if you move your cursor to the first position then try executing your for loop the cursor will try to move to the next position before you even process the first position. This is why you dont enter the for loop when you have 1 thing in the cursor

Solution 2:

The -1 index in cursors is the default starting position and the fallback position. Calling moveToFirst will always move to position 0 if it exists. You want to make sure if you do use moveToFirst, you process that entry then call moveToNext.

if(cursor.moveToFirst()){ // moves to 0, process it.process(...);
  while(cursor.moveToNext()){ // moves to 1...n, process them.process(...);
   }
 }

That is just one way to approach it, hope it helps.

Good Luck

Solution 3:

I suspect that default cursor position was intentionally set to -1 to make us able to iterate with just while(cursor.moveToNext()) {...}. There is no other reasons to have negative positions of cursor.

You don't need to reset position to -1 as long as you haven't affect this cursor before.

Solution 4:

-1 is the default position of a cursor and you always need to move the cursor to the first position ie 0th index. To perform your activity

cursor.moveToFirst(); //moves the cursorto the first position

Now to iterate

while(cursor.moveToNext())//when there's a value in cursor.moveToNext
{
//your action to be performed
}

Post a Comment for "How Can An Android Cursor Be At A Negative Position?"