Search code examples
javaandroidsqlsqlitecursor

Android SQLite: CursorIndexOutOfBoundsException when retrieving a row from a table?


I keep getting android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 exception when trying to get a single row from a Sqlite table using a ID value.

Why do you think this happens? What is wrong with my code?

public Product getProduct(DBOps dop, String productId) {

        Product p = new Product();
        String sqlQuery = "SELECT " + TableInfo.PID + " FROM "
  + TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'"; 
        SQLiteDatabase SQ = dop.getReadableDatabase();
        Cursor CR = SQ.rawQuery(sqlQuery, null);

        try
        {
            if(CR.getCount() > 0)
            {
                while (!CR.isAfterLast()) {
                    p.PID = CR.getString(0);
                    p.NAME = CR.getString(1);
                    p.SIZE = CR.getString(2);
                    p.COLORS = CR.getString(3);
                    p.DESC = CR.getString(4);
                    p.PRICE= CR.getString(5);
                    p.OUTLETS = CR.getString(6);
                    p.FABRIC = CR.getString(7);
                    p.QUANTITY = CR.getString(8);
                    p.CATEGORY = CR.getString(9);
                    p.RATING = CR.getString(10);

                    CR.moveToNext();
                }
            }
            else
            {
                CR.close();
            }
        }
        catch(Exception ex)
        {
            Log.e("DBOps Error", "Look at DBOps Class's getProduct Method");
            Log.e("DBOps Error", ex.toString());
        }
        return p;
    }

Solution

  • android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

    Because you are currently selecting only one column from table which is TableInfo.PID but trying to retrieve more then one column from cursor.

    So change select query by specify all columns in select query or use * FROM get all columns:

    String sqlQuery = "SELECT * FROM "
      + TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'";