Retrieving data from the database

Open TodoListDBHelper, and add the method shown as follows:

fun retrieveTaskList(): ArrayList<Task> {
val db = this.readableDatabase // 1

val projection = arrayOf<String>(BaseColumns._ID,
TodoListDBContract.TodoListItem.COLUMN_NAME_TASK,
TodoListDBContract.TodoListItem.COLUMN_NAME_DEADLINE,
TodoListDBContract.TodoListItem.COLUMN_NAME_COMPLETED) // 2

val cursor = db.query(TodoListDBContract.TodoListItem.TABLE_NAME, projection,
null, null, null, null, null) // 3

val taskList = ArrayList<Task>()
// 4
while (cursor.moveToNext()) {
val task = Task(cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID)),
cursor.getString(cursor.getColumnIndexOrThrow(TodoListDBContract.TodoListItem.COLUMN_NAME_TASK)),
cursor.getString(cursor.getColumnIndexOrThrow(TodoListDBContract.TodoListItem.COLUMN_NAME_DEADLINE)),
cursor.getInt(cursor.getColumnIndexOrThrow(TodoListDBContract.TodoListItem.COLUMN_NAME_COMPLETED)) == 1)
taskList.add(task)
}
cursor.close() // 5

return taskList
}

In the retrieveTaskList method, we perform the following:

  1. We first retrieve the database in read-mode. 
  2. Next, we create an array that lists all the columns of the table we need to retrieve. Here, if we have no need for the values of a specific column, we don't add that.
  3. We then pass the table name and the column list to the query() method on the database object. This returns a Cursor object. 
  4. Next, we loop through the items in the Cursor object, and create an instance of the Task class with the attributes of each item.
  5. We close the cursor and return the retrieved data

Now, open MainActivity, and add the following line of code at the beginning of thpopulateListView() method:

    todoListItems = dbHelper.retrieveTaskList();

Your populateListView() method should now look like this:

private fun populateListView() {
todoListItems = dbHelper.retrieveTaskList();
listAdapter = TaskListAdapter(this, todoListItems)
listView?.adapter = listAdapter
}

Now, build and run again. You'll notice that, unlike in the previous chapter, when you restarted the application, the tasks you saved earlier are preserved:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset