I\'m using the SQLite with Android, and I want to know the best way to get the generated id of the row I inserted.
A solution I think makes a search after include, b
If use ContentValues :
DBHelper db =new DBHelper();// your dbHelper
ContentValues values = new ContentValues();
values.put("firstName","Ahmad");
values.put("lastName","Aghazadeh");
long insertedId= db.getSQLiteDatabase().insert("user", "", values) ;
If query exec use select last_insert_rowid()
String sql = "INSERT INTO [user](firstName,lastName) VALUES (\"Ahmad\",\"Aghazadeh\"); select last_insert_rowid()";
DBHelper itemType =new DBHelper();// your dbHelper
c = db.rawQuery(sql, null);
if (c.moveToFirst())
result = c.getLong(0);
If use Room
@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
@Dao
public interface UserDao{
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
// Insert multiple users
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insert(User... user);
}