Pre-populate Room database

Gonzalo Martin
AndroidPub
Published in
2 min readDec 28, 2017

--

→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!

--

--