インターフェイスで使用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
また、クエリを使用してこれを行うことができる複数の方法があります。
- 1つは@DiegoTorresMilanoによって表されます
SELECT MAX(id) FROM table_name
。または、すべての列の値を取得しますSELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name)
。
PRiMARY KEY
に座っている場合AUTOINCREMENT
は、SELECT
maxからminに応じて値を設定し、を使用して行を1に制限SELECT id FROM table ORDER BY column DESC LIMIT 1
できます(すべての値が必要な場合は、*
の代わりにを使用してくださいid
)