AndroidPub
Published in

AndroidPub

Pre-populate Room database

→This article is out of date and it needs be upgraded ←

This is a quick and simple article in how can you pre-populate your Room database at first run.

First of all, if you didn’t read about Room database, you can review this post:

Pre-populate

Sometimes is very helpful have a pre-loaded data to start to use an application that uses a database as storing data. Room has a way to pre-populate the database at first run. The trick is override the onCreate method in Room callback:

void onCreate (SupportSQLiteDatabase db)

So, let’s suppose we have an entity like this:

public class DataEntity {

private String imageUrl;
private String title;
private String text;

public DataEntity(String imageUrl, String title, String text) {
this.imageUrl = imageUrl;
this.title = title;
this.text = text;
}
// getters and setters

And a DAO with two methods:

@Dao
public interface DataDao {

@Query("SELECT * FROM DataEntity")
List<DataEntity> getAll();

@Insert
void insertAll(DataEntity... dataEntities);
}

Nice, now we can create our AppDatabase that extends of RoomDatabase class. Here we should add our callback to know when database is created

Remember use a separate thread when you insert elements into database. Finally, this is the populateData method implementation

public static DataEntity[] populateData() {
return new DataEntity[] {
new DataEntity("image1.jpg", "title1", "text1"),
new DataEntity("image2.jpg", "title2", "text2"),
new DataEntity("image3.jpg", "title3", "text3"),
new DataEntity("image4.jpg", "title4", "text4"),
new DataEntity("image5.jpg", "title5", "text5")
};
}

In the first call to AppDatabase.getInstance(context) this code will be executed.

You can review the full implementation of these classes:

And that’s all! Very quick and easy to implement!

Questions or suggestions? Post a comment below! Happy coding!

--

--

--

The (retired) Pub(lication) for Android & Tech, focused on Development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gonzalo Martin

Gonzalo Martin

Mobile Technical Lead at @GlobalLogic_LA https://github.com/gonzalonm

More from Medium

Android AdMob consent with UMP — Personalized or Non-Personalized Ads in EEA

Rx SwitchMap, Check before dispose

Cheat Sheet for Java programmers to get started with Kotlin

How to create a new inspection for IDEA