Pre-populate Room database

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

Pre-populate

void onCreate (SupportSQLiteDatabase db)
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
@Dao
public interface DataDao {

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

@Insert
void insertAll(DataEntity... dataEntities);
}
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.

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

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