In SQLiteOpenHelper
there is a onCreate(SQLiteDatabase ...)
method which i used to populate database tables with some initial data.
Is there a way to insert some data into Room database table on first app run?
Prepopulate from the file systembuild(); The createFromFile() method accepts a File argument for the prepackaged database file. Room creates a copy of the designated file rather than opening it directly, so make sure your app has read permissions on the file.
Room vs SQLiteRoom provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In the case of SQLite, There is no compile-time verification of raw SQLite queries. But in Room, there is SQL validation at compile time.
Updated
You can do this in 3 ways: important check this for migration details
1- Populate your database from exported asset schema
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db") .createFromAsset("database/myapp.db") .build();
2- Populate your database from file
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db") .createFromFile(new File("mypath")) .build();
3- You can run scripts after database is created or run every time database is opened using RoomDatabase.Callback
, this class is available in the latest version of the Room library.
You need to implement onCreate
and onOpen
method of RoomDatabase.Callback
and add it to RoomDatabase.Builder
as shown below.
yourDatabase = Room.databaseBuilder(context, YourDatabase.class, "your db") .addCallback(rdc) .build(); RoomDatabase.Callback rdc = new RoomDatabase.Callback() { public void onCreate (SupportSQLiteDatabase db) { // do something after database has been created } public void onOpen (SupportSQLiteDatabase db) { // do something every time database is open } };
Reference
You can use Room DAO itself in the RoomDatabase.Callback methods to fill the database. For complete examples see Pagination and Room example
RoomDatabase.Callback dbCallback = new RoomDatabase.Callback() { public void onCreate(SupportSQLiteDatabase db) { Executors.newSingleThreadScheduledExecutor().execute(new Runnable() { @Override public void run() { getYourDB(ctx).yourDAO().insertData(yourDataList); } }); } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With