Iterate through rows from Sqlite-query

AndroidSqliteDatabase Cursor

Android Problem Overview


I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data.

I use this code to populate the TextViews inside the table rows.

Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, 
		 R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);

I want to be able to separate the four different values of KEY_ALT, and choose where they go. I want them to populate four different TextViews instead of one in my example above.

How can I iterate through the resulting cursor?

Android Solutions


Solution 1 - Android

Cursor objects returned by database queries are positioned before the first entry, therefore iteration can be simplified to:

while (cursor.moveToNext()) {
    // Extract data.
}

Reference from SQLiteDatabase.

Solution 2 - Android

You can use below code to go through cursor and store them in string array and after you can set them in four textview

String array[] = new String[cursor.getCount()];
i = 0;

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
	array[i] = cursor.getString(0);
	i++;
	cursor.moveToNext();
}

Solution 3 - Android

for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
    // use cursor to work with current item
}

Solution 4 - Android

Iteration can be done in the following manner:

Cursor cur = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME, null);
ArrayList temp = new ArrayList();
if (cur != null) {
    if (cur.moveToFirst()) {
        do {
            temp.add(cur.getString(cur.getColumnIndex("Title"))); // "Title" is the field name(column) of the Table   				
        } while (cur.moveToNext());
    }
}

Solution 5 - Android

Found a very simple way to iterate over a cursor

for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){


    // access the curosr
    DatabaseUtils.dumpCurrentRowToString(cursor);
    final long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));


}

Solution 6 - Android

I agree to chiranjib, my code is as follow:

if(cursor != null && cursor.getCount() > 0){
  cursor.moveToFirst();
  do{
    //do logic with cursor.
  }while(cursor.moveToNext());
}

Solution 7 - Android

public void SQLfunction() {
    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String[] sqlSelect = {"column1","column2" ...};
    String sqlTable = "TableName";
    String selection = "column1= ?"; //optional
    String[] selectionArgs = {Value}; //optional

    qb.setTables(sqlTable);
    final Cursor c = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null);
    
   if(c !=null && c.moveToFirst()){
        do {
           //do operations
           // example : abcField.setText(c.getString(c.getColumnIndex("ColumnName")))
             
          }
        while (c.moveToNext());
    }


}

NOTE: to use SQLiteQueryBuilder() you need to add

compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+' in your grade file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkakka47View Question on Stackoverflow
Solution 1 - AndroidhappydudeView Answer on Stackoverflow
Solution 2 - Androidchikka.anddevView Answer on Stackoverflow
Solution 3 - AndroidJuozas KontvainisView Answer on Stackoverflow
Solution 4 - AndroidchiranjibView Answer on Stackoverflow
Solution 5 - AndroidpasssyView Answer on Stackoverflow
Solution 6 - AndroidJason HView Answer on Stackoverflow
Solution 7 - AndroidDeepak KatariaView Answer on Stackoverflow