如何将Room Persistence Library与预填充的数据库一起使用? [英] How to use Room Persistence Library with pre-populated database?
问题描述
我想将Room与预填充的数据库一起使用,但是我不明白如何告诉Room在哪里可以找到我的数据库.
I'd like to use Room with a pre-populated database, but I can't understand how to tell Room where to find my database.
我现在将它放在src/main/assets/databases
中,当我为Room数据库创建实例时,我是这样创建的:
I've now put it in src/main/assets/databases
and when I create the instance for the Room database I create it this way:
Room.databaseBuilder(
getApplicationContext(),
AppDatabase.class,
"justintrain.db"
)
.allowMainThreadQueries()
.build();
通过这种方式,我认为它每次都会创建一个新数据库,或者无论如何,它都没有使用预先填充的数据库.
This way tho, I think it's creating a new database every time, or anyways, it's not using the pre-populated one.
如何才能找到我的数据库?
How can I make it to find my database?
推荐答案
这就是我解决的方法,以及如何使用预先填充的数据库(不超过Room v.alpha5)运送应用程序
This is how I solved it, and how you can ship your application with a pre-populated database (up to Room v. alpha5)
-
将您的SQLite数据库
database_name.db
放入assets/databases
文件夹
从此存储库中获取文件 并将它们放入名为ie sqlAsset
的程序包中
take the files from this repo and put them in a package called i.e. sqlAsset
,相应地修改Room的数据库创建代码:
in your AppDatabase
class, modify your Room's DB creation code accordingly:
Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class,
"database_name.db")
.openHelperFactory(new AssetSQLiteOpenHelperFactory())
.allowMainThreadQueries()
.build();
请注意,您必须使用"database_name.db"
而不是getDatabasePath()
或其他方法:它只需要文件名.
Note that you have to use "database_name.db"
and not getDatabasePath()
or other methods: it just needs the name of the file.
这篇关于如何将Room Persistence Library与预填充的数据库一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!