DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. Introduction to Android App Development With Kotlin: Retrieve Data From Room (Part 9)

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.

Łukasz Mądrzak user avatar by
Łukasz Mądrzak
CORE ·
Apr. 29, 19 · Tutorial
Like (2)
Save
Tweet
Share
8.07K Views

Join the DZone community and get the full member experience.

Join For Free

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.

app Data (computing) Android (robot) Kotlin (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
  • Using JSON Web Encryption (JWE)
  • The 31 Flavors of Data Lineage and Why Vanilla Doesn’t Cut It
  • Data Mesh vs. Data Fabric: A Tale of Two New Data Paradigms

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: