I'm making a small application in android with kotlin, I'm pretty new at this... I've already created the database, the table, I do the insert, but I would like to make a select from that table in an activity and show the data. .. I do not get it...
This is my code to get the users
//función para obtener usuarios
fun getUsers(): ArrayList<User> {
val usuarios = ArrayList<User>()
val db = writableDatabase
val selectQuery = "SELECT * FROM NOMBRE_TABLA"
val cursor = db.rawQuery(selectQuery, null)
if (cursor != null) {
cursor.moveToFirst()
while (cursor.moveToNext()) {
val nombre = cursor.getString(cursor.getColumnIndex(COL_NOMBRE))
val apellidos = cursor.getString(cursor.getColumnIndex(COL_APELLIDOS))
val usuario = User(nombre, apellidos)
usuarios.add(usuario)
}
}
cursor.close()
return usuarios
}
}
I think it returns them correctly, but now I don't know how to return them to the view... This is my method in my activity
fun listado(){
var db = Database(this, "pacDesarrollo", null, 1)
db.getUsers()
}
I've managed not to fail me, but I don't know how I should show them...
I think I have found the solution to display them. a listView
but when trying to display my data there, the LogCat returns the following error:
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
And since I am creating the adapter, it is:
fun listado() {
var db = Database(this, "pacDesarrollo", null, 1)
val users = db.getUsers()
adaptador1 = ArrayAdapter(this, android.R.layout.activity_list_item, users)
vista.setAdapter(adaptador1)
}
Thank you and regards
If you are going to use the layout of the "item" SDK you must do it in this way
If you use a custom layout called
activity_list_item
, you will do it like this: