babiro
babiro

Reputation: 85

How to resolve android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

I've searched for solutions for a long time and still can't find a relevant way to make it work.
I have this method inside an external myDBClass.java in Android studio to find last inserted row.

public Cursor lastrow() {
    // TODO Auto-generated method stub
    try{
         SQLiteDatabase db;
         db = this.getReadableDatabase(); // Read Data
         String query = "SELECT ID As _id, Spinpos, Details, Setfor from alarm order by ID DESC limit 1";
         Cursor cursor = db.rawQuery(query, null);
         if(cursor != null)
            {
                cursor.moveToFirst();
                return cursor;
            }
            else
            {
                return null;
            }

         } catch (Exception e) {
           return null;
         }
      }

Then I execute it in MainActivity.java

 myDBClass myDb = new myDBClass(this);      
 Cursor cursor  = myDb.lastrow();  
 String SongID = cursor.getString(cursor.getColumnIndex("Spinpos"));  
 Toast.makeText(this,SongID,Toast.LENGTH_LONG).show();  

It throws android.database.CursorIndexOutOfBoundsException. Please provide me a solution.

Upvotes: 0

Views: 362

Answers (2)

Giacomo Lai
Giacomo Lai

Reputation: 494

Cursor is initialized to position -1, so when you call moveToNext() will return true if the cursor reach position 0, that mean the db fetched at least one value.

Use this

 if(cursor.moveToNext()){

     //database fetched at least one value
 }

Upvotes: 1

Panczur
Panczur

Reputation: 651

You also need to check that your cursor has result, something like this:

if (cursor != null && cursor.getCount() > 0)

Upvotes: 0

Related Questions