开发者社区> 问答> 正文

getReadableDatabase()不能在ui线程进行?

以前我一贯的写法是getReadableDatabase()和getWritableDatabase() 都是在ui线程进行的,而且在android4.0以上版本都没有任何问题,最近换了个android2.2的设备测试,发现就报错了,异常是SQLiteException 并提示database is locked这些信息,检查我对数据库的操作只不过是写完数据后读数据,应该不存在数据库被锁的问题。
思前想后,在SQLiteOpenHelper 源代码中发现到getReadableDatabase()的如何注解
/*

  • Create and/or open a database. This will be the same object returned by
  • {@link #getWritableDatabase} unless some problem, such as a full disk,
  • requires the database to be opened read-only. In that case, a read-only
  • database object will be returned. If the problem is fixed, a future call
  • to {@link #getWritableDatabase} may succeed, in which case the read-only
  • database object will be closed and the read/write object will be returned
  • in the future.
    **

    Like {@link #getWritableDatabase}, this method may

    • take a long time to return, so you should not call it from the
    • application main thread, including from
    • {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.*
    • @throws SQLiteException if the database cannot be opened
    • @return a database object valid until {@link #getWritableDatabase}
    • or {@link #close} is called.
      */

留意高亮部分,注解说不要写在应用的主线程,包括contentprovider的oncreate方法,我好奇的是 网上大家都是直接写在ui线程,而且看上去是可行的 为什么官方的api注解却提示不可以。还有一个奇怪的问题,就是我说过的遇到的那个异常并不是必定的,是偶尔出现的
so 说下你们的见解吧

展开
收起
a123456678 2016-07-18 14:18:17 2179 0
1 条回答
写回答
取消 提交回答
  • android的设计就是,不让任何耗时的操作阻塞UI线程……
    所有操作DB和网络请求的操作,尽量另起线程。
    在以前的版本中,貌似要求不是那么严格。但是现在android对这个要求很严格…………

    我的理解,本身android的效率已经被IOS甩在后面了,所以我们做开发的就不要在给android找不愉快了。把耗时操另起线程,是一个良好的习惯……

    2019-07-17 19:57:50
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用TensorFlow搭建智能开发系统自劢生成App UI代码 立即下载
Fusion Design - 企业级UI解决方案揭秘 立即下载
使用TensorFlow搭建智能开发系统自动生成App UI 立即下载