通过从 assert 复制数据库文件在 Room 中使用预先填充的数据库

Ale*_*exS 3 filestream populate android-sqlite android-room

我想在 Android Room 中使用预先填充的数据库。我找到了一种通过使用回调来实现它的方法,并填充了数据库文件。但是出了点问题,我确定数据库复制正常,但在设备监视器和android模拟器中它仍然为空。你能帮我么

public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
private static final String DB_NAME = "base.db";
static Context ctx;

public abstract Dao dao();

public static AppDatabase getDatabase(Context context) {
    if (INSTANCE == null) {
        ctx = context;
        synchronized (AppDatabase.class) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context,
                        AppDatabase.class, DB_NAME)
                        .allowMainThreadQueries()
                        .addCallback(rdc)
                        .build();
            }
        }
    }
    return INSTANCE;
}

private static RoomDatabase.Callback rdc = new RoomDatabase.Callback() {
    public void onCreate(SupportSQLiteDatabase db) {

        new PopulateDbAsync(INSTANCE, ctx).execute();
        Log.d("db create ", "table created when db created first time in  onCreate");
    }

    public void onOpen(@NonNull SupportSQLiteDatabase db) {
        ContentValues contentValues = new ContentValues();
    }
};

private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {

    private Dao dao;
    AssetManager assetManager = ctx.getAssets();

    PopulateDbAsync(AppDatabase db, Context context) {
        Dao = db.Dao();
        ctx = context;
    }

    @Override
    protected Void doInBackground(final Void... params) {
        String DB_PATH = "/data/data/mypackage/databases/";
        String DB_NAME = "base.db";
        try {
            Log.d("AppDatabase","Trying copy database file");
            OutputStream myOutput = new FileOutputStream(DB_PATH + DB_NAME);
            byte[] buffer = new byte[1024];
            int length;
            InputStream myInput = ctx.getAssets().open("base.db");
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            myInput.close();
            myOutput.flush();
            myOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

kdb*_*lue 5

我在研究和研发上花了6个小时解决了。

上下文是: - 我想将已经存在的 finaldb.db(存在于assests 文件夹中)放入房间数据库。

第 1 步: 从这里链接复制此框架文件

第 2 步: 您需要迁移,冷静,我有代码 :)

@Database(entities = {Status.class}, version = 1,exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract DataDao StatusDao();

    private static AppDatabase INSTANCE;


    public static AppDatabase getDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE = createDatabase(context);
        }
        return (INSTANCE);
    }

    private static final Migration MIGRATION_2_3 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            Log.d("kkkk","bc");

            String SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS 'Status' " +
                    "( 'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
                    "  'category' TEXT NOT NULL," +
                    "  'sub_category' TEXT NOT NULL," +
                    "  'content' TEXT NOT NULL," +
                    "  'favourite' INTEGER DEFAULT(0))";

            database.execSQL(SQL_CREATE_TABLE);

        }
    };

    private static AppDatabase createDatabase(Context context) {
        RoomDatabase.Builder<AppDatabase> builder =
                Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class,
                        context.getString(R.string.dbase_name));


        return (builder.openHelperFactory(new AssetSQLiteOpenHelperFactory())
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_2_3)
                .build());
    }

}
Run Code Online (Sandbox Code Playgroud)

在 MIGRATION_2_3 中,您必须创建与当前数据库完全相同的表(存在于资产文件夹中)

想了解移民

第3步: 现在房间数据库中的表已成功创建!

如果发生崩溃,请查看您的 logcat,其中以可理解的形式编写。