如何将 Room Persistence Library 与预先填充的数据库一起使用? [英] How to use Room Persistence Library with pre-populated database?

查看:33
本文介绍了如何将 Room Persistence Library 与预先填充的数据库一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 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 DB database_name.db 放入 assets/databases 文件夹

从这个 repo 中取出文件 并将它们放入一个名为 的包中sqlAsset

take the files from this repo and put them in a package called i.e. sqlAsset

在您的 AppDatabase 类中,相应地修改 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屋!

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