Search code examples
androidsqlitecursor

Sqlite Cursor not getting data from database


I am trying a simple insert and read operation but I am getting exception while doing it so.

Here is the code i am trying,

try{
    SQLiteDatabase db = openOrCreateDatabase("iTimeDB", MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS Activities (ID INTEGER PRIMARY KEY AUTOINCREMENT ,IMEI VARCHAR, Title VARCHAR, Time VARCHAR);");
    db.execSQL("INSERT INTO Activities(IMEI, Title, Time) VALUES('"+ IMEI +"','"+ title +"','" +time+"');");
    Cursor c = db.rawQuery("SELECT MAX(ID) FROM Activities", null);
    c.moveToFirst();
    String ID = c.getString(c.getColumnIndex("ID"));
    Log.v("column: ID", ID);
    db.close();

    }
    catch(Exception e)
    {
        e.printStackTrace();
        Log.v("YYY", e.toString());
    }

There is no exception while inserting data but when I try to read from DB here is the Exception

Here is the LogCat

01-02 11:02:46.992: V/YYY(20510): java.lang.IllegalStateException: Couldn't read row
0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before
accessing data from it.

Solution

  • Try this way

    String ID = c.getInt(0);
    

    OR

    Cursor c = db.rawQuery("SELECT MAX(ID)'ID' FROM Activities", null);
        c.moveToFirst();
        String ID = c.getString(c.getColumnIndex("ID"));