Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android cursor.moveToNext()?

I am trying to query all the columns in a table into one long text view and/or string. I know this might not be the right way to do things but I have to do this. Correct me if I am wrong, I was under the impression that move next would get the next column in the row:

Cursor c = db.get();
if(c.moveToFirst){
  do{
    string = c.getString(0);
  }while(c.moveToNext);
}

I thought that this would get the first column and display all of its contents instead I get the first column and first row. What am I doing wrong? Is there a better or real way to get this information without using a ListView?

like image 759
Christian Avatar asked Apr 10 '12 00:04

Christian


People also ask

What is cursor moveToNext ()?

moveToNext() Move the cursor to the next row.

What does cursor moveToFirst do?

Calling moveToFirst() does two things: it allows you to test whether the query returned an empty set (by testing the return value) and it moves the cursor to the first result (when the set is not empty).

What is Android cursor?

Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set.

What is SQLite open helper in Android?

SQLiteOpenHelper class The android. database. sqlite. SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.


2 Answers

cursor.moveToFirst() moves the cursor to the first row. If you know that you have 6 columns, and you want one string containing all the columns, try the following.

c.moveToFirst();
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < 6; i++){
   stringBuilder.append(c.getString(i));
}

// to return the string, you would do stringBuilder.toString();
like image 160
Raunak Avatar answered Sep 27 '22 18:09

Raunak


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.

like image 26
mrd Avatar answered Sep 27 '22 19:09

mrd