Kirmani88 Kirmani88 - 6 months ago 30
Android Question

Fetching data from sqlite database returning no records

A row is inserted successfully in database. I export

sqlite
database file and it shows me the record. Now i am trying to fetch that record from database. Database only has 1 record.

String containerData = "";

SQLiteDatabase db= this.getReadableDatabase();
Cursor cursor= db.rawQuery("select "+ " * " + " from "+ TABLE_NAME, null);

if(cursor != null){
cursor.moveToFirst();
while(cursor.moveToNext()){
containerData= cursor.getString(0);
}

cursor.close();
db.close();


I have tried to use db.query(), also tried to remove while loop and used following.

containerData= cursor.getString(0);


but this gives me following error message


Method threw 'android.database.CursorIndexOutOfBoundsException
exception.


There are total 5 columns in my table.

Answer Source

Try out the following code:

 String containerData = "";

 SQLiteDatabase db= this.getReadableDatabase();
 Cursor cursor= db.rawQuery("select "+ " * " + " from "+ TABLE_NAME, null);

 if(cursor != null){
    cursor.moveToFirst();    

    while (!cursor.isAfterLast()){
        containerData= cursor.getString(0);
        cursor.moveToNext();
        Log.d("ShowData->", containerData);
    }
 }

 cursor.close();
 db.close();