0

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.

7
  • Firstly i would recommend switching from raw sql , and to a more faster and friendlier approach ORM, realm for android is no-sql and is much faster and easier to maintain Commented Apr 13, 2017 at 11:07
  • the easiest way is Cursor cursor= db.rawQuery(...); if(cursor.moveToFirst()) { do { /*do something with cursor*/ } while(cursor.moveToNext());} cursor.close() there is no need for null check from rawQuery Commented Apr 13, 2017 at 11:08
  • And i would not recomend ORM as Cursors has lower memory footprint using fx CursorAdapter is much faster then loading all objects into POJO and using CustomAdapter Commented Apr 13, 2017 at 11:10
  • @Selvin @Remario : WIll this be more efficient if i use this db.query(TABLE_NAME, new String[]{COLUMN_NAME}, null,null,null,null,null); Commented Apr 13, 2017 at 11:13
  • Possible duplicate of What's the best way to iterate an Android Cursor? Commented Apr 13, 2017 at 11:15

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

You check cursor only for null, you need to check if there is any values in that cursor too:

if (cursor != null && !cursor.isAfterLast()){
...
}

1 Comment

!cursor.isAfterLast() is returning true, and when i export the file, it shows the record in the table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.