Get last inserted value from sqlite database Android

Viewed 74836

I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work. This is my method:

 public Cursor getLastId() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}

I have tried with MAX, but I must be using it wrong. Is there another way?

10 Answers

If you want the last_insert_id just afert a insert you can use that :

public long insert(String table, String[] fields, String[] vals ) 
{
    String nullColumnHack = null;
    ContentValues values = new ContentValues();
    for (int i = 0; i < fields.length; i++) 
    {
        values.put(fields[i], vals[i]); 
    }

    return myDataBase.insert(table, nullColumnHack, values);
}

I use this

public int lastId(){
    SQLiteDatabase db =  
  this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from resep", null );
    res.moveToLast();
    return res.getInt(0);
}

In your DbHelper class,

    public long getLastIdFromMyTable()
    {
        SQLiteDatabase db = this.getReadableDatabase();
        SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
        return st.simpleQueryForLong();
    }
Related