2012-06-13 137 views
4

我有運行讀寫SQLite數據庫多線程綁定服務。我創建了一個我的數據庫幫助程序的實例,並在我的服務的onCreate中獲得數據庫連接,這應該在主線程上執行。因爲它是一個綁定服務,所以應該只有一個服務實例在內存中。但是,當服務試圖打開數據庫或其中一個線程嘗試執行語句時,偶爾我仍會遇到異常。Android的SQLite數據庫被鎖定

服務代碼:

@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

發表您的服務完整的源代碼....... –

+2

以及正常數據庫時,已經是正在與數據庫中的一個線程,所以可能你的一個線程正在與數據庫,你忘了被鎖關閉連接。 – Raykud

+0

[添加到Raykud答案] ...或者你跳過密切關係的代碼有一個例外。 – k3b

回答