以前我一贯的写法是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.
** <p class="caution">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 说下你们的见解吧