尝试重新打开已经关闭的数据库的房间 [英] Room attempt to re-open an already closed database

查看:124
本文介绍了尝试重新打开已经关闭的数据库的房间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Android Architecture组件使用Room时,尝试使用Dagger组件访问数据库时收到以下错误:

When using Room from the Android Architecture Components, I received the following error when attempting to access the database using a Dagger component:

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: (database path)

我正在使用Dagger版本2.11和Room版本1.0.0-alpha7.该错误在版本1.0.0-alpha5上是可重现的.

I was using Dagger version 2.11 and Room version 1.0.0-alpha7. The error was reproducible on version 1.0.0-alpha5.

初始化数据库并将其注入我的类后,通过DAO尝试访问数据库时都会发生此错误.

This error occurred on any attempt to access the database through a DAO after initialising the database and injecting it into my class.

推荐答案

这是因为您试图在不提供任何迁移信息的情况下修改现有数据库的架构.因此,基本上,它尝试将新的数据库架构写入不起作用的现有数据库.

It's because you are trying to modify the schema of the existing database without giving it any migration information. So basically it attempts to write the new database schema to the existing DB which doesn't work.

有两种解决方法.如果您处于开发环境中,那么您可以做的是回退到破坏性的迁移,为此,您的数据库创建代码将类似于以下内容:

There are two ways around this. If you are in your development environment what you can do is fallback to a destructive migration, to do this your database creation code would look something like the following:

MyDatabase myDatabase = Room.databaseBuilder(context, MyDatabase.class, "my-db")
    .fallbackToDestructiveMigration()
    .build();

这意味着,当您向数据库提供更新的实体或新实体时,它将按照@huw的回答进行操作,只删除应用程序安装中的数据库,删除其中的所有数据,然后进行全新安装.

This means when you provide the database with an updated or new entity it will do what the answer from @huw said and just delete the database on the application's installation removing all the data from it and give you a fresh install.

另一种方法是使用迁移功能.它们很长,因此除非有人要我在这里写下,否则我将暂时保留,但基本上可以在这里找到文档:

The other method is to use a migration function. They are pretty long so unless someone wants me to write it up here I'll leave it for now but basically, the documentation can be found here:

Room DB迁移文档

从本质上讲,这将导致数据库运行您自己提供的某些SQL,以将数据库更新为新版本.这样,您可以确保在进行迁移时不会丢失任何数据.或根据您的工作而尽可能少.这是生产应用程序的首选方法,因为这意味着用户不会丢失其先前存在的数据,并且您不会收到很多生气的评论/失去的客户.

This essentially causes the DB to run some SQL provided by yourself to update the database to the new version. This way you can ensure that none of your data is lost while doing the migration; or as little as possible depending on what you are doing. This is the preferred method for production apps as it means users won't lose their pre-existing data and you won't get a lot of angry reviews/lost customers.

希望能有所帮助!

这篇关于尝试重新打开已经关闭的数据库的房间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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