我有一个运行多个线程的绑定服务,可以读写SQLite数据库。我创建了一个数据库助手的实例,并在我的服务的onCreate中获得了与数据库的连接,该连接应该在主线程上执行。因为它是绑定服务,所以应该只在内存中存在一个服务实例。但是我还是得到了 服务尝试打开数据库或其中一个线程尝试执行语句时偶尔会出现异常。
服务代码:
@Override
public void onCreate() {
super.onCreate();
MyDatabaseHelper helper = new MyDatabaseHelper(this);
database = helper.getWritableDatabase();
}
例外:
java.lang.RuntimeException: Unable to create service uk.co.example.service.MyService:
android.database.sqlite.SQLiteException: unable to open database file
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1959)
at android.app.ActivityThread.access$2500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:989)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3691)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: unable to open database file
at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1960)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:887)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:965)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:958)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:585)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)
at uk.co.example.service.MyService.onCreate(MyService.java:69)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1949)
... 10 more
android.database.sqlite.SQLiteException: error code 5: database is locked
at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
at uk.co.example.a.a.a.a(MyTable.java:147)
at uk.co.example.service.b.a.m.run(MySaveTask.java:84)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
任何可能导致此问题的想法?
由于
大卫
答案 0 :(得分:0)
Sqlite现在支持一种名为Writing-Ahead Logging的新日志模式,它适用于对sqlite的并发访问。你可能想看看http://www.sqlite.org/wal.html。