Reader small image

You're reading from  Mastering Kotlin for Android 14

Product typeBook
Published inApr 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781837631711
Edition1st Edition
Languages
Right arrow
Author (1)
Harun Wangereka
Harun Wangereka
author image
Harun Wangereka

Harun Wangereka is a Google Developer Expert for Android and an Android engineer with over seven years of experience and currently working at Apollo Agriculture. Harun is passionate about Android development, never tired of learning, building the tech community, and helping other developers upscale their skills. He is a co-organizer at Droidcon Kenya and a former Kotlin Kenya and Android254 co-organizer. Through these communities, he has been able to impact thousands of developers. He is also an Android author at Kodeco where he has written 8 articles, published a book; Saving Data on Android, Second Edition, and is also a video course instructor. He has given numerous sessions on Android and Kotlin across different communities worldwide.
Read more about Harun Wangereka

Right arrow

Persisting Data Locally and Doing Background Work

To provide better user experiences, we must ensure that apps don’t fetch data every time the user opens the app. At times, the user can be in areas that do not have internet access, and this can be very frustrating when the user can’t use your app in such situations. For such scenarios, we have to store data locally. We also have to store and update the data in an efficient way that doesn’t drain the device’s battery or block the user from doing other things on the app. In this chapter, we will be exploring how to do so for our apps.

In this chapter, we will learn how to save data to a local database, Room, which is part of the Jetpack libraries. We will be able to save items and read from the Room database. Additionally, we will learn how to do long-running operations using WorkManager and some of the best practices.

In this chapter, we’re going to cover the following main topics:

  • Saving...

Technical requirements

To follow the instructions in this chapter, you will need to have Android Studio Hedgehog or later (https://developer.android.com/studio) downloaded.

You can use the previous chapter’s code to follow the instructions in this chapter. You can find the code for this chapter at https://github.com/PacktPublishing/Mastering-Kotlin-for-Android/tree/main/chaptereight.

Saving and reading data from a local database

We are going to build up on the Pets app, which displays a list of cute cats. We will save our cute cats in a local database, Room, which is a part of the Android Jetpack libraries and provides a wrapper and abstraction layer over SQLite. We will also use the repository pattern to abstract away the data source from ViewModel. The Room database provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. It also has inbuilt support for Kotlin coroutines and flows to allow for asynchronous database access. Room is also compile-time safe and hence any errors in SQL queries are caught at compile time. It allows us to do all this with concise code.

To use Room in our project, we need to add its dependency to our libs.versions.toml file. Let us start by defining the Room version in the versions section as the following:

room = "2.5.2"

Next, let us add the dependencies in...

Handling updates and migrations in the Room database

FavoritePetsScreen doesn’t have any functionality yet. We are going to add the functionality to favorite pets and update this information in the Room database. To achieve this, we need to do the following:

  • Set up a Room schema directory.
  • Add a new column to our CatEntity class to store the favorite status of the cat.
  • Add a new function to CatDao to update the favorite status of the cat.
  • Update our UIs with a favorite icon and, once clicked, update the favorite status of the cat. This means the ViewModel and repository classes will also be updated in the process.

Let’s get started with the steps:

  1. Let us start by setting up the schema directory. In our app level build.gradle.kts file, add the following code:
    ksp {
        arg("room.schemaLocation", "$projectDir/schemas")
    }

    Do a Gradle sync and then build the project. This generates a schema json file...

Using WorkManager to schedule background tasks

WorkManager is a Jetpack library that is best suited for performing long-running tasks in the background. It ensures that background tasks are completed even when your app restarts or the phone restarts. With WorkManager, you can either schedule one-time jobs or recurring jobs.

We will start by adding the WorkManager dependency to our project. Follow these steps:

  1. Let us head over to the libs.versions.toml file and define the work version in our versions section as follows:
    work = "2.8.1"
  2. In the libraries section, add the following dependencies:
    work-runtime = { module = "androidx.work:work-runtime-ktx", version.ref = "work" }
    workmanager-koin = { module = "io.insert-koin:koin-androidx-workmanager", version.ref = "koin" }

    Here, we have two dependencies: the work-runtime-ktx dependency, which is the core dependency for WorkManager, and the koin-androidx-workmanager dependency,...

Testing your workers

Testing the code is very important. It ensures that our code works as expected and it also helps us to catch bugs early. We will be writing tests for our workers in this section. To test our workers, we first need to set up WorkManager testing dependencies with the following steps:

  1. Let us head over to the libs.versions.toml file and add the following dependency to the libraries section:
    work-testing = { module = "androidx.work:work-testing", version.ref = "work" }

    Sync your project. This will add the work-testing artifact that helps in testing workers to our project.

  2. Next, we need to add the dependency to our app level build.gradle.kts file:
    androidTestImplementation(libs.work.testing)

    We have used androidTestImplementation because we will be writing our tests in the androidTest folder. Do a Gradle sync to add the dependency to our project. We are now ready to start writing our tests.

Since our PetsSyncWorker class requires some...

Summary

In this chapter, we learned how to save data to a local database, Room, which is part of the Jetpack libraries. We also saved items and read from the Room database. In the process, we also learned how to update items in the Room database and how to handle automated migrations in our database. Additionally, we learned how to do long-running operations using WorkManager, its best practices, and how to write tests for our workers.

In the next chapter, we will learn about runtime permissions and how to request them in our app.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Kotlin for Android 14
Published in: Apr 2024Publisher: PacktISBN-13: 9781837631711
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Harun Wangereka

Harun Wangereka is a Google Developer Expert for Android and an Android engineer with over seven years of experience and currently working at Apollo Agriculture. Harun is passionate about Android development, never tired of learning, building the tech community, and helping other developers upscale their skills. He is a co-organizer at Droidcon Kenya and a former Kotlin Kenya and Android254 co-organizer. Through these communities, he has been able to impact thousands of developers. He is also an Android author at Kodeco where he has written 8 articles, published a book; Saving Data on Android, Second Edition, and is also a video course instructor. He has given numerous sessions on Android and Kotlin across different communities worldwide.
Read more about Harun Wangereka