我想在应用程序第一次启动时在我的数据库上添加一些行(大约180个)。我找到了一些Executors.newSingleThreadExecutor()
的教程,如https://android.jlelse.eu/pre-populate-room-database-6920f9acc870。但是有没有其他方法来预先填充数据库?
AppDatabase.class
@Database(entities = {Country.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public abstract CountryDao countryDao();
public synchronized static AppDatabase getInstance(Context context) {
if (INSTANCE == null)
INSTANCE = buildDatabase(context);
return INSTANCE;
}
private static AppDatabase buildDatabase(final Context context) {
return Room.databaseBuilder(context, AppDatabase.class, "countries").allowMainThreadQueries().addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
getInstance(context).countryDao().insertAll(Country.populateData());
}
});
}
}).build();
}
}