Pre-Populate Room Database

Abdullaherzincanli
Huawei Developers
Published in
5 min readMay 30, 2023
Source

Introduction

HišŸ‘‹, have you ever had a data class that you only needed for reading purposes in the application development process, and you had to save it to the database only onceā“ Let me explain what I meanā“ Have you ever had a large data set with hundreds of elements that you created while writing your code, but you didnā€™t need to use all of them at onceā“ These hundreds or even thousands of data stored in memory, donā€™t they pose a risk for memory management and memory leaksā“ Doesnā€™t it increase the processing load unnecessarily when you need to pass these data to other activities and fragmentsā“ So, how can we solve thisā“ In this article, I will discuss one of the solutions to this issue, letā€™s get startedšŸ™ƒ.

What is Prepopulateā“

ā€œPrepopulate room databaseā€ means adding predetermined data to a Room database. This allows you to have default or ready-made data in the database when you start your application or start using the database for the first time.

The prepopulate process is performed when the application is launched or at the moment the database is created. It allows adding pre-defined data to the database while creating the database tables and relationships. This way, users can access predetermined data when they open the application or use the database.

Typically, a series of data or a JSON file is used for the prepopulate process. These files contain predefined data to populate the database according to the model. You can add this data to the database using Room DAOs and database operations.

For example, when creating an application for countries and their flags, we can quickly provide users with the records of all countries and flags by loading the database that we created when the application starts.

The prepopulate process can improve the user experience and make your application more usable. It also facilitates application testing and development process by using prepopulated data.

Source

How to Use ā“

Letā€™s create a simple example database scenario to demonstrate the usage of Room. Letā€™s say we want to create a movie database application and store the name, director, and release year of the movies.

  1. Step: Creating the Database Object

First, you need to create the database object. For this, you need to create a class that extends the Room Database class. Letā€™s create a class called ā€œMovieDatabaseā€ as an example:

Create Film Database Class

In the above example, we specify the path of the database file to be used for prepopulation using the createFromAsset method. The database file should be located under the assets folder.

2. Step: Creating the Entity Class

You need to create an entity class for each item in your database. Let's create an entity class called "Movie" as an example:

Film Data Class

Thanks to our Movie class, we have displayed the content of our table.

3. Step: Creating the Access Point Object

To access the database, you need to create a DAO (Data Access Object) class. This class contains methods that define the database queries. Letā€™s create a DAO class called ā€œFilmDaoā€ as an example:

FilmDao

We defined the process of adding a movie to the database using the @Insert annotation, and we defined the process of retrieving all movies using the @Query annotation.

4. Step: Using the Database Object

In the final step, you can use the database object. Letā€™s perform the database operations in the MainActivity class as an example:

MainActivity for database process

In the above example, we obtain the database object using the FilmVeritabani.getInstance() method. Then, we perform the database operations. In this example, we add a new movie using the filmekle() method and retrieve all movies using the tumFilmleriAl() method.

Thanks to the prepopulate feature, by using the createFromAsset() method, you will have pre-defined data filled in the database when the application is launched.

Source

I would like to talk about the migration feature in addition to what I have mentioned.

The migration process is typically used in two scenarios:

  1. Upgrading the database version: You make structural changes to the database schema and create a new version. For example, you may add a column or delete an existing column.
  2. Changing the database schema: It is used when you want to completely change the database structure. In this case, you would remove the existing database entirely and create a new database.

To perform the migration process, you can follow the steps below:

  1. Specify the migration strategy in the database class:
  • Update the version parameter in the Database annotation in the database class to indicate the new version number.
  • Use the fallbackToDestructiveMigration() or addMigrations() method to specify the migration strategy.
Migration Example

In the example above, we preferred to use the fallbackToDestructiveMigration() method, which deletes the existing database completely and recreates it with each version update.

Alternatively, you can define a more complex migration strategy using the addMigrations() method. With this method, you can manage the differences between the old and new database schemas by defining Migration classes.

Here are the steps to define Migration classes:

Extend the Migration class: Create a new class that extends the Migration class. Implement the migrate() method: Override the migrate() method to define the necessary database schema changes between the old and new versions.

By defining Migration classes, you can perform more granular and controlled changes to the database schema during version upgrades.

Migrations Class Example

In the given example, we defined two migration classes named MIGRATION_1_2 and MIGRATION_2_3. These classes perform the necessary operations to make the old database schema compatible with the new schema in their migrate() methods.

You can customize the Migration classes according to your needs. For example, you can add or remove columns, perform data transformations, and carry out other operations within these classes.

By using the migration feature in Room, you can make your database compatible with version upgrades. This allows you to evolve the database schema over time while preserving existing data and ensuring the smooth functioning of your application.

By defining and applying appropriate migration classes, you can ensure that your database seamlessly transitions from one version to another, maintaining data integrity and ensuring a smooth user experience.

Using the migration feature in Room enables you to keep your database up to date with evolving requirements and make it compatible with version updates.

Conclusion

During the application development process, one of the challenges I faced was efficiently managing data that needed to be consistently available to the user, even without an internet connection. I needed a solution that would allow me to store and retrieve this data across all fragments within the application without relying on static classes. Pre-populating the database provided a suitable solution to this problem.

By recording the necessary data into the local database when the application is first launched, I was able to retrieve and utilize that data throughout the entire application without the need to recreate it. This approach ensured that the application could function seamlessly, even when offline.

Throughout this project, I have learned a lot, and I hope it can be equally beneficial to all of you. Stay healthy and keep coding! šŸ‘Øā€šŸ’»šŸ™‹ā€ā™‚ļø

References

--

--