Использование moveToLast()
в Cursor
интерфейсе.
С 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();
Простой пример:
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
}
Или вы можете получить последнюю строку при вставке (о которой упоминал @GorgiRankovski):
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
Также есть несколько способов сделать это с помощью запроса:
- Один выражается @ DiegoTorresMilano
SELECT MAX(id) FROM table_name
. или получить все значения столбцов SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name)
.
- Если ваш
PRiMARY KEY
сел на AUTOINCREMENT
, вы можете SELECT
vaules occording до макс. / Мин. И ограничить ряды до 1, используя SELECT id FROM table ORDER BY column DESC LIMIT 1
(Если вам нужно каждое значение, используйте *
вместо id
)