How can an Android cursor be at a negative position?

六月ゝ 毕业季﹏ 提交于 2019-12-24 11:14:07

问题


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; cursor.moveToNext(); i++) {
  //do something with the cursor
}

While mathematically this makes sense, I don't know what it means to move to a cursor to a negative position. The documentation just says it's valid–doesn't seem to say how it's used.

Is this used ONLY to make iteration possible, or is there other use cases for the position -1?


回答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




回答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




回答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.




回答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 cursor to the first position

Now to iterate

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


来源:https://stackoverflow.com/questions/27530128/how-can-an-android-cursor-be-at-a-negative-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!