Room - 何时初始化数据库以及如何通过应用程序生命周期访问它

时间:2017-07-28 12:31:13

标签: android sqlite android-room

我正在尝试设置Room以简化对SQLite数据库的访问。我已经编写了一些代码,但我无法运行它,因为app会抛出以下异常:

  

无法访问主线程上的数据库,因为它可能会长时间锁定UI

我做了一些研究,我发现.allowMainThreadQueries() databaseBuilder favorite I am trying to add a bottom border image (red curved triangle) to each item of navigation bar. So far I used css border-image property. I managed to add the item. The problem is that it is stretching. Is there a way to prevent them from stretching while having them centered? /** * Layout */ .nav__list { margin: 0; padding: 0; } .nav__list a { padding: .75em 1.5em; transition: all .25s ease-in-out; } .nav__list__item { border-style: solid; border-width: 0 0 1px; } .nav__list__item, .nav__list__item a { display: block; } /** * Desktop-view */ @media screen and (min-width: 1024px) { .nav__list > .nav__list__item { border-width: 0 1px 0 0; } .nav__list > .nav__list__item, .nav__list > .nav__list__item a { display: inline-block; } } /** * Presentation */ .nav { background-color: #f5f5f5; } .nav .nav__list__item { border-color: #e5e5e5; } .nav a { color: #555; text-decoration: none; width:100%; position:relative; } .nav li:hover a:after{ width:10%; margin:0 auto; position:absolute; content:""; border-bottom: solid #000; border-image: url('https://www.dropbox.com/s/qa8qzjqqo8oa926/curved-triangle.png?raw=1') 0 0 100 0; border-image-width: 15; border-image-outset: 10; bottom:0px; left:50%; }在我看来似乎是一个糟糕的解决方案,因为它就像静音错误信息,而不是修复真正的原因。

那么,最佳做法是什么?什么时候(在应用程序生命周期中)我应该创建我的数据库,我应该在哪里存储它,以便我可以从我想要的任何活动中访问它?

1 个答案:

答案 0 :(得分:1)

  

何时(在应用程序生命周期中)我应该创建我的数据库

在第一次访问时懒惰创建RoomDatabase,就像直接使用SQLiteOpenHelper一样。

  

我应该把它存放在哪里

单身将是一种典型的模式,就像直接使用SQLiteOpenHelper一样。

这些问题都与错误消息无关。这是在后台线程上访问数据库的问题,就像直接使用SQLiteOpenHelper时一样。对于@Query方法,您可以选择让方法返回LiveData或RxJava类型(例如,Flowable),在这种情况下,Room将负责处理背景线程。对于其他操作(例如,@Insert),您负责自己在后台线程上调用这些方法(ThreadAsyncTaskThreadPoolExecutorIntentServiceJobIntentService等。)。