问题
I am writing a android application using sqlite
. There are many activities and one service. I use the DB from more than one thread. It works perfectly in Android 2.X
, but once I run it in Android 3.X
it always throws this error and Force Close
:
05-04 22:17:04.815: I/SqliteDatabaseCpp(8774): sqlite returned: error code = 5, msg = database is locked, db=/data/data/xxx/databases/im
05-04 22:17:04.815: E/SqliteDatabaseCpp(8774): sqlite3_open_v2("/data/data/xxx/databases/im", &handle, 6, NULL) failed
05-04 22:17:04.835: E/SQLiteDatabase(8774): Failed to open the database. closing it.
05-04 22:17:04.835: E/SQLiteDatabase(8774): android.database.sqlite.SQLiteDatabaseLockedException: database is locked
05-04 22:17:04.835: E/SQLiteDatabase(8774): at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
05-04 22:17:04.835: E/SQLiteDatabase(8774): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:983)
05-04 22:17:04.835: E/SQLiteDatabase(8774): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:956)
05-04 22:17:04.835: E/SQLiteDatabase(8774): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1021)
05-04 22:17:04.835: E/SQLiteDatabase(8774): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:790)
05-04 22:17:04.835: E/SQLiteDatabase(8774): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
05-04 22:17:04.835: E/SQLiteDatabase(8774): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:149)
Anyone knows why it happen and how to solve it?
I have researched in the internet and most people advise:
- Use one DB connection only for the application. How to ensure it? I want to share the DB connection for both of the Service and Activities. Should I do it by create a public static DB variable?
- ContentProvider - I am using complicated SQL Statement in code (Such as joining few tables, temporary table). Is it possible to run these complicated SQL statement in ContentProvider?
Thank you everyone. Finally, (1) works fine for me. But I still wonder why Android 2.X does not have this problem.
回答1:
Number 1 is the answer. I have several stack answers and blog posts about how exactly to do that:
What are the best practices for SQLite on Android?
http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection
Number 2 is a lot of extra work and unnecessary. ContentProvider exists so you can share data with other apps. Its used to manage database connections because people don't understand how Sqlite and Android work together.
回答2:
I suggest you use a ContentProvider
with a LoaderManager
whenever you can. It is capable of performing queries in the background automatically.
来源:https://stackoverflow.com/questions/10450977/android-sqlite-with-multi-thread