简体   繁体   中英

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

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM