'How to fetch data from multiple columns in sqlite android using cursor

I want to fetch data from multiple rows and columns using curser using this below code

  Cursor getallrecords(){

    SQLiteDatabase dbb = this.getReadableDatabase();

    Cursor cursor = null;

    if (dbb != null){
        Log.d("cursor","not null");
      
        cursor = dbb.rawQuery(" SELECT * FROM " + TABLE_NAME,null);

        }else{
        Log.d("cursor","null");
    }

    return cursor;
    }

On logcat it shows the cursor is not empty and returns data. But when I try to set that data which cursor carries on ArrayList using the below code.

  void read(){
    Cursor cursor = save_barcode.getallrecords();

    if (cursor.getCount() != 0){
        cursor.moveToFirst();
        while(cursor.moveToNext()){
            url.add(cursor.getString(1));
            type.add(cursor.getString(2));
            date_and_time.add(cursor.getString(3));
        }
    }

    if (!url.isEmpty()){
        Log.d("message","not null");
    }else {
        Log.d("url","null");
    }

    if (!type.isEmpty()){
        Log.d("message","not null");
    }else {
        Log.d("type","null");
    }
    if (!date_and_time.isEmpty()){
        Log.d("message","not null");
    }else {
        Log.d("date","null");
    }
}

Then in logcat it shows URL,date_and_time, type all of these three are empty. So if anyone knows how to fetch data from multiple rows and column using cursor then help me



Solution 1:[1]

The obvious problem with your code is that you are using moveToFirst() and after that moveToNext(), so it is certain that you lose the 1st row.
If all you have in the table is just 1 row then the lists will be empty.
No need to check getCount(), so remove if and no need for moveToFirst().

Change to this:

void read(){
    Cursor cursor = save_barcode.getallrecords();
    if (cursor == null) return; 
    while (cursor.moveToNext()) {
        url.add(cursor.getString(1));
        type.add(cursor.getString(2));
        date_and_time.add(cursor.getString(3));
    }
    cursor.close();

   ...................
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 forpas