Sử dụng moveToLast()
trong giao diện Cursor
.
Từ 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();
ví dụ đơn giản:
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
}
Hoặc bạn có thể nhận hàng cuối cùng khi chèn (Đó là @GorgiRankovski đã đề cập):
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
Ngoài ra họ là nhiều cách bạn có thể thực hiện việc này bằng truy vấn:
- Một được biểu thị bằng @DiegoTorresMilano
SELECT MAX(id) FROM table_name
. hoặc để lấy tất cả các giá trị cột SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name)
.
- Nếu
PRiMARY KEY
bạn đã ngồi để AUTOINCREMENT
, bạn có thể SELECT
vaules occording để tối đa để chuẩn tối thiểu và hạn chế các hàng tới 1 sử dụng SELECT id FROM table ORDER BY column DESC LIMIT 1
(Nếu bạn muốn mỗi giá trị, sử dụng *
thay vì id
)
Phương thức chèn trả về hàngId hoặc -1 http://stackoverflow.com/questions/5409751/get-generated-id-after-insert – rds
xem https://stackoverflow.com/a/40962443/1770868 –