Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to Android App Development With Kotlin: Retrieve Data From Room (Part 9)

DZone 's Guide to

Introduction to Android App Development With Kotlin: Retrieve Data From Room (Part 9)

Check out the ninth part of the series on Android app development, focusing on retrieving data from the Room database.

· Java Zone ·
Free Resource

You’ve come so far on your app development journey and I wish to congratulate you. We’re not far from reaching the end of these series, but there are still a few more things we must do before we call our app functional and useful. We are yet to discuss fetching data from Room, lists, recycler views, adapters, and LiveData.

In the previous part, we stored data in the database, and now, it’s the time to retrieve it.

Select All

Similar to inserting data, retrieving is also quite simple. In the  NewMovieViewModel, we will implement another method named retrieveMovies(). For now, this method will not return anything but will make a call to the database, retrieve all the times, and then print the number of the items we have currently stored into LogCat.

fun retrieveMovies() {

    val list = mDb?.movieDao()?.getAll()

    Timber.i("retrieveMovies list count {${list?.size}}")

}


It’s a very simple method, but unfortunately, we will stop our project from successfully compiling.

That’s because we haven’t done much printing to LogCat just yet, and in order to do that, we will need a library called Timber (https://github.com/JakeWharton/timber). As always, we must first import the library in the build.gradle file:

// Timber
implementation 'com.jakewharton.timber:timber:4.7.1'


With Timber imported, we must “plant a tree” that will allow our logs to be printed. We want to plant a DebugTree, which will ensure that logs are only printed when in debug mode. It’s an actual crime to have logs printed in a production app because it greatly affects the performance.

In MainActivity, in the onCreate method, add:

Timber.plant(Timber.DebugTree())


Now that our project compiles again, if you paid attention in the previous tutorial, you would know that our app will crash if we call the retrieveMovies method as it is trying to access the database on the main thread. Let’s fix the retrieveMovies method by adding a coroutine

fun retrieveMovies() {

    GlobalScope.launch {
        val list = mDb?.movieDao()?.getAll()
        Timber.i("retrieveMovies list count {${list?.size}}")
    }
}


Now, we are ready to go. Let’s call it from theMovieListFragment as that’s where we will eventually be displaying the complete list of movies persisted in the database.

First, we must add a member variable that we will initialize in the onCreate method

private lateinit var mViewModel: NewMovieViewModel


Now, initialize it in the same fashion as we did in theNewMovieFragment:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Create a ViewModel the first time the system calls an activity's onCreate() method.
    // Re-created activities receive the same MyViewModel instance created by the first activity.

    mViewModel = ViewModelProviders.of(this).get(NewMovieViewModel::class.java)

}


With access to the database through the ViewModel, we can find out how many items we have stored in the database and finally prove that we really are storing those movies! Simply call the retrieveMovies() method:

mViewModel.retrieveMovies()


Run the app, launch the LogCat and pay attention to the results you get. Here’s my console output

Image title

I then added another movie entry, and the outcome was this:

Image title

Turn off the app, launch it again, and you should get the same result because the data is persisted “for good.” Your boss asked for undeniable proof that the database is working and here it is!

Conclusion

In this tutorial, we have learned how to fetch the stored data, how to print data to LogCat using Timber, and we practiced the usage of coroutines. In the next tutorial, we will learn about LiveData and discuss the reasons for why we should use it. We will, therefore, improve our ViewModel and make the code base even better.

The complete working code can be found in this GitHub repo where each lesson is tagged appropriately.

Topics:
kotlin 1.3 ,kotlin ,android app developement ,room ,room database ,mvvm ,java ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}