0

This is what i am using for insert:

 public long insert(String content, Date startAt, Date endAt) {
        if (content == null || startAt == null) {
            return 0;
        }

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_CONTENT, content);
        contentValues.put(KEY_START_AT, startAt.getTime());
        if (endAt == null) {
            contentValues.putNull(KEY_END_AT);
        } else {
            contentValues.put(KEY_END_AT, endAt.getTime());
        }

        return sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
    }

now i want to create update method which will update last inserted row. How can i get last inserted row?

Nermeen
  • 15,883
  • 5
  • 59
  • 72
senzacionale
  • 20,448
  • 67
  • 204
  • 316
  • Here's another question with a similiar problem: http://stackoverflow.com/questions/7575166/android-sqlite-get-last-insert-row-id – r0- Mar 06 '13 at 12:49
  • http://stackoverflow.com/questions/7575166/android-sqlite-get-last-insert-row-id Refer this link for getting last inserted row – Nirmal Mar 06 '13 at 13:07

4 Answers4

1

You can use a cursor to retrieve rows and say :

   cursor.moveToLast();

OR

  cursor.moveToPosition(cursor.getCount() - 1);
Divya Motiwala
  • 1,659
  • 1
  • 16
  • 24
1

If you have an id attribute that works as a primary key, you can do a raw database query on SqlLite.

Cursor cc = this.mDb.rawQuery("SELECT *" + " FROM " + "<Your DATABASE_NAME> " + 
"ORDER BY id " + "DESC LIMIT 1", null);
return cc;

Here, 1. It returns a cursor. 2. mDb is a SQLiteDatabase class instance. 3. ORDER BY id allows the query to sort by id number. As I said, if you have an id as primary key in your table, your latest entry will have the maximum id number. 4. DESC allows to sort by descending order. 5. LIMIT 1 allows to return only 1 row. 6. Always be careful when writing raw queries, white spaces inside the query can be a lot of pain when you do not handle them carefully.

For further queries you can see this tutorial. And obviously Divya's answer is also a good one.

Taslim A. Khan
  • 516
  • 1
  • 8
  • 26
0

When you insert a row in to your table the insert query returns the key of the last inserted row. You can now use this key to update this row.

for example

int newInsertedKey = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);

update table_name set column_name = 'Change 2' where columnID = newInsertedKey

An efficient method would be to avoid anymore database queries to get the last updated row.

user_CC
  • 4,686
  • 3
  • 20
  • 15
0

Maybe he should use something like this

public long getLastId() {
    Cursor c = mDb.query(currentTableName, new String[] { "MAX(_id)" },
            null, null, null, null, null, null);

            try{
    c.moveToFirst();
    long id = c.getLong(0);
    return id;
            }catch(Exception e){
              return 0;
            }

}

where _id is column by which you identify rows