Use moveToLast()
en Cursor
interfaz.
De android.googlesource.com
/**
* Move the cursor to the last row.
*
* <p>This method will return false if the cursor is empty.
*
* @return whether the move succeeded.
*/
boolean moveToLast();
ejemplo simple:
final static String TABLE_NAME = "table_name";
String name;
int id;
//....
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(cursor.moveToLast()){
//name = cursor.getString(column_index);//to get other values
id = cursor.getInt(0);//to get id, 0 is the column index
}
O puede obtener la última fila cuando (se han mencionado, que es @GorgiRankovski) de inserción:
long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred
También su es una forma múltiple de hacerlo con la consulta:
- Uno se expresa por @DiegoTorresMilano
SELECT MAX(id) FROM table_name
. o para obtener todos los valores de las columnas SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name)
.
- Si su
PRiMARY KEY
se han sentado a AUTOINCREMENT
, puede SELECT
vaules occording al máximo a min y limitar las filas a 1 utilizando SELECT id FROM table ORDER BY column DESC LIMIT 1
(Si desea todos y cada valor, utilice *
en lugar de id
)
El método de inserción devuelve rowId o -1 http://stackoverflow.com/questions/5409751/get-generated-id-after-insert – rds
ver https://stackoverflow.com/a/40962443/1770868 –