如何在第一次运行时填充 Android Room 数据库表? [英] How to populate Android Room database table on first run?
问题描述
在 SQLiteOpenHelper
中有一个 onCreate(SQLiteDatabase ...)
方法,我用来用一些初始数据填充数据库表.
In SQLiteOpenHelper
there is a onCreate(SQLiteDatabase ...)
method which i used to populate database tables with some initial data.
有没有办法先将一些数据插入到 Room 数据库表中应用运行?
Is there a way to insert some data into Room database table on first app run?
推荐答案
更新
您可以通过 3 种方式执行此操作:重要检查此迁移详细信息
You can do this in 3 ways: important check this for migration details
1- 从导出的资产架构中填充您的数据库
1- Populate your database from exported asset schema
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
.createFromAsset("database/myapp.db")
.build();
2- 从文件中填充您的数据库
2- Populate your database from file
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
.createFromFile(new File("mypath"))
.build();
3- 您可以在创建数据库后运行脚本或使用 RoomDatabase.Callback
打开数据库时运行脚本,该类在最新版本的 Room 库中可用.
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.
你需要实现RoomDatabase.Callback
的onCreate
和onOpen
方法并添加到RoomDatabase.Builder
如下图.
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
}
};
您可以在 RoomDatabase.Callback 方法中使用 Room DAO 本身来填充数据库.有关完整示例,请参阅分页和房间示例
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);
}
});
}
};
这篇关于如何在第一次运行时填充 Android Room 数据库表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!