Converting database cursor into list of objects
In the previous recipe, we learned how to query data from a database table. We receive a cursor as result of the query. In this recipe, we will learn how to use parseList
to convert the cursor into a list of objects.
Getting ready
I'll be using Android Studio 3 to write code. You can get started by adding anko-sqlite dependencies to your project and creating a database helper like we did in the Using SQLite database in Kotlin recipe.
How to do it…
Follow these steps to convert the cursor into a list of objects:
- Let's start by creating a
Customer
class as a model for ourcustomers
table:
data class Customer(val id: Int, val name: String, val phone_num: String) { companion object { val COLUMN_ID = "id" val TABLE_NAME = "customers" val COLUMN_NAME = "name" val COLUMN_PHONE_NUM = "phone_num" } }
- Now we will write code to create the
customers
table inside the database helper class. Check out the following code:
class...