会议室数据库强制执行OnCreate回调 [英] Room Database force OnCreate callback

查看:80
本文介绍了会议室数据库强制执行OnCreate回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RoomDatabase开发一个应用程序,该应用程序需要预先填充其数据;我已经设法通过添加onCreate()回调来做到这一点,但是只有在第一次访问数据库时才调用它(例如调用Daos函数之一).

I'm developing an application with RoomDatabase that needs to pre-populate its data; I already managed to do it by adding the onCreate() callback, but it gets called only when accessing the database the first time (like calling one of the Daos functions).

是否有任何方法可以在不执行任何读或写操作的情况下强制创建数据库?

Is there any way to force the database creation without doing any read or write operation?

那是我的代码,MyDatabase.get()App.onCreate()

@Database(entities = {Entity1.class, Entity2.class}, version = 1, exportSchema = true)
public abstract class MyDatabase extends RoomDatabase {

    private static MyDatabase sInstance;

    public synchronized static TaxCodeDatabase get(Context context) {
        if (sInstance == null) {
            sInstance = buildDatabase(context);
        }
        return sInstance;
    }

    private static MyCodeDatabase buildDatabase(final Context context) {
        return Room.databaseBuilder(context,
                MyCodeDatabase.class,
                "my-database")
                .addCallback(new Callback() {
                    @Override
                    public void onCreate(@NonNull SupportSQLiteDatabase db) {
                        super.onCreate(db);
                        sInstance.preFillData(context);
                      });
                    }
                })
                .build();
    }

    public abstract Entity1Dao entity2Dao();

    public abstract Entity2Dao entity1Dao();

    /**
     * Populates the database with a series of initial data
     *
     * @param aContext
     */
    public void prePopulateData(Context aContext) {
        //Populate database here
    }

推荐答案

是否有任何方法可以在不执行任何读或写操作的情况下强制创建数据库?

Is there any way to force the database creation without doing any read or write operation?

不,抱歉.

但是,没有什么可以阻止您在调用Room之前将预先填充的数据库复制到适当位置.您需要确保预先填充的数据库中包含Room的元数据(例如,通过使用Room本身创建该数据库).

There is nothing stopping you from copying the pre-populated database into position before invoking Room, though. You would need to ensure that the pre-populated database has Room's metadata in it (e.g., by creating that database using Room itself).

这篇关于会议室数据库强制执行OnCreate回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆