如何在Android Room中完全重新创建数据库? [英] How do I completely recreate my database in Android Room?

查看:969
本文介绍了如何在Android Room中完全重新创建数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的情况,我希望能够使用Android Room进行数据库的硬重置.使用SQLiteOpenHelper,我可以通过编写一种方法来删除所有表和索引,然后手动调用SQLiteOpenHelper.onCreate().

I have a situation where I want to be able to do a hard reset of my database using Android Room. Using SQLiteOpenHelper, I could do this by writing a method to drop all tables and indices, then manually call SQLiteOpenHelper.onCreate().

我知道我可以通过房间访问SupportSQLiteOpenHelper并自己放下所有桌子,但是似乎没有一个启动娱乐过程的好​​方法.

I'm aware that I can get access to a SupportSQLiteOpenHelper via room and drop all the tables myself, but there doesn't seem to be a good way to kick-off the recreation process.

此外,我知道我可以删除每个表中的每个项目而不删除它,但这不是我想要的.这不会重置自动递增的主键,因此新项目的"id"字段不会重置为1.

Also, I'm aware that I could delete every item from each table without dropping it, but that's not what I want. That doesn't reset the auto-incrementing primary key, so the "id" field of new items won't reset back to 1.

谢谢!


这是我希望能够在运行时任意执行的操作.


This is something I want to be able to do arbitrarily at runtime.


该方法应可维护,即不涉及与Room行为匹配的手写SQL.理想情况下,将有某种方法可以检索 Room生成的SQL,或者是一种SQLiteOpenHelper.onCreate()等效方法.或其他解决此问题的方法! :)

EDIT 2:
The method should be maintainable, i.e. not involve hand-writing SQL that matches Room's behavior. Ideally there would be some way to retrieve the SQL that Room generates, or a SQLiteOpenHelper.onCreate() equivalent method. Or anything else that solves this problem! :)

推荐答案

我发现最简单的方法是通过context.deleteDatabase("name"),然后通过Room.databaseBuilder().addCallback重新实例化并重新填充数据库首次访问.

I found it easiest to do this via context.deleteDatabase("name") and then simply reinstantiating and repopulating the database via the Room.databaseBuilder().addCallback upon first access.

这篇关于如何在Android Room中完全重新创建数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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