Question Detail

How to get last inserted row ID in SQlite android

6 years ago Views 3614 Visit Post Reply

I am using SQLite for store my Android Application's Local Data when I reach on next Screen I am Inserting Data in Table but if my process complete inserted Id should be deleted or if User leave process in between it store in the local database.

How to get last Inserted Rows ID in my SQLite Database?


Thread Reply

Hemant Sharma

- 6 years ago

The insert method returns the id of a row just inserted or -1 if there was an error during insertion.

// Adding new album
public void addAlbum(DataClass data) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, data.getAlbumName()); // Album Name
    values.put(KEY_DES, data.getDescription()); // Album Description

    // Inserting Row
    long id =db.insert(TABLE_ALBUMS, null, values);
    System.out.println("Inserted ID : "+id);
    db.close(); // Closing database connection
}

db is an instance of your SQLiteDatabase.

Hemant Sharma

- 6 years ago

The insert method returns the id of a row just inserted or -1 if there was an error during insertion.

// Adding new album
public void addAlbum(DataClass data) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, data.getAlbumName()); // Album Name
    values.put(KEY_DES, data.getDescription()); // Album Description

    // Inserting Row
    long id =db.insert(TABLE_ALBUMS, null, values);
    System.out.println("Inserted ID : "+id);
    db.close(); // Closing database connection
}

db is an instance of your SQLiteDatabase.