android cursor.moveToNext()? android cursor.moveToNext()? sql sql

android cursor.moveToNext()?

The simple use is:

Cursor cursor = db.query(...);while (cursor.moveToNext()) {    ...}

moveToFirst is used when you need to start iterating from start after you have already reached some position.

Avoid using cursor.getCount() except if it is required.And never use a loop over getCount().

getCount is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.

If your query matches 1000 rows, the cursor actually has only the first row. Each moveToNext searches and finds the next match. getCount must find all 1000. Why iterate over all if you only need 10? Why iterate twice?

Also, if your query doesn't use an index, getCount may be even slower - getCount may go over 10000 records even though the query matches only 100. Why loop 20000 instead of 10000?

For clarity a complete example would be as follows which I trust is of interest. As code comments indicated we essentially iterate over database rows and then columns to form a table of data as per database.

    Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null,            null);    //if the cursor isnt null we will essentially iterate over rows and then columns    //to form a table of data as per database.    if (cursor != null) {        //more to the first row        cursor.moveToFirst();        //iterate over rows        for (int i = 0; i < cursor.getCount(); i++) {            //iterate over the columns            for(int j = 0; j < cursor.getColumnNames().length; j++){                 //append the column value to the string builder and delimit by a pipe symbol                stringBuilder.append(cursor.getString(j) + "|");             }            //add a new line carriage return            stringBuilder.append("\n");            //move to the next row            cursor.moveToNext();        }        //close the cursor        cursor.close();    }

I am coding my loops over the cusror like this:

    cursor.moveToFirst();    while(!cursor.isAfterLast()) {            cursor.getString(cursor.getColumnIndex("column_name"));        cursor.moveToNext();    }

That always works. This will retrieve the values of column "column_name" of all rows.Your mistake is that you loop over the rows and not the columns.To loop over the columns:

cursor.moveToFirst();        for(int i = 0; i < cursor.getColumnNames().length; i++){        cursor.getString(i);    }

That will loop over the columns of the first row and retrieve each columns value.