简书链接:room数据库初始化细节
文章字数:185,阅读全文大约需要1分钟
Room

1
2
3
4
5
AppDatabase database = AppDatabase.getInstance(this, new AppExecutors());
TemplateDao templeteDao = database.templeteDao();
List<PrintTemplate> printTemplates = templeteDao.queryTemplateByField("title", "Box");//不查询就不触发自动,真贱
Log.w(TAG,"PrintTemplate:"+printTemplates);//这里不能关闭数据库,否则将无法正常初始化。

如果在application的初始化中直接close,那么也会导致初始化失败,初始化的地方是回调。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private static AppDatabase buildDatabase(final Context appContext,
final AppExecutors executors) {
return Room.databaseBuilder(appContext, AppDatabase.class, DATABASE_NAME)
.allowMainThreadQueries()//允许主线程查询
.setJournalMode(JournalMode.WRITE_AHEAD_LOGGING)
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
executors.diskIO().execute(() -> {
// Add a delay to simulate a long-running operation 添加延迟以模拟长时间运行的操作

if(BuildConfig.DEBUG){
Log.w("Appdatabase","DATABASE_INIT");
}
// Generate the data for pre-population 生成预人口数据
AppDatabase database = AppDatabase.getInstance(appContext, executors);
List<PrintTemplate> templeteEntries = DataGenerator.generateTempletes();
insertData(database, templeteEntries);
// notify that the database was created and it's ready to be used MutableLiveData flag=true
database.setDatabaseCreated();

});
}
})
.addMigrations(MIGRATION_1_2)//迁移
.build();
}

如上可以看到是在

1
2
3
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {

里面触发的,但是关闭就会导致初始化基本上失败的,关闭了还不影响我查询操作,但是初始化失败的,关于该不该关闭的问题网上也有各种说法,