Reputation: 3276
I am trying to get the last added or inserted record in the sqlite database/table based on the auto increment "id" Integer, but my app keeps crashing.
Here is my Kotlin code.
@SuppressLint("Range")
fun getLast(): Int {
val db = databaseHelper.readableDatabase
val cursor = db.rawQuery("SELECT * FROM sensor WHERE MAX(id)",null)
if (cursor.count>0) {
cursor.movetofirst()
return cursor.getInt(cursor.getColumnIndex("id")) <---- FAILS and app crashes.
}
}
An arrow pointing to the offending like is the cause of my app failure.
However, in other functions I do exactly that for different columns and it works no problem at all like the following.
// iterate through the cursor and add the data to the list
while (cursor.moveToNext()) {
val Sensor_name = cursor.getString(cursor.getColumnIndex("sensor_name")) <----- This line works.
val Sensor_reading = cursor.getString(cursor.getColumnIndex("sensor_reading")) <----- This line works.
list.add(Sensor(Sensor_name, Sensor_reading))
}
So, how do you search and retrieve auto increment ID column from SQLite database/table using SQL in Kotlin?
Upvotes: 0
Views: 56