我一直得到這惱人的運行時錯誤幾個小時,墜毀我的應用程序:什麼時候應該關閉SQLiteDatabase對象?
了java.lang.RuntimeException:執行 doInBackground發生錯誤()。
產生的原因:java.lang.IllegalStateException:嘗試 重新打開已關閉的對象:SQLiteDatabase
一些調試,我發現這是因爲我閉上SQLiteDatabse對象後,在onDestory()
方法。當我撥打SQLiteOpenHelper.close()
時也會發生這種情況。
@Override
protected void onDestroy() {
super.onDestroy();
_cursor.close(); //is fine
_db.close(); //causes error
_databaseHelper.close(); //causes error too (probably calls db.close() internally..?)
SharedFunctions.d("closed!"); //ignore this ugly thing
}
這帶來了兩個問題
- 我這樣做對嗎? (可能不是)
- 當我需要關閉SQLiteDatabase對象,如果不是在
onDestroy
方法?
編輯: 的DB和輔助類是靜態的:
public class MainActivity extends Activity {
private Cursor _cursor = null;
private MyCursorAdapter _myCursorAdapter = null;
private ListView _listView = null;
private static SalaryDatabaseHelper _databaseHelper = null;
public static SQLiteDatabase db = null;
...
我初始化_databaseHelper在onCreate()方法:
//get database helper
if(_databaseHelper == null)
_databaseHelper = SalaryDatabaseHelper.getInstance(this);
db
在AsyncTask.doInBackground()
被初始化:
protected Boolean doInBackground(Integer... data)
{
try {
//get writable database
if(db == null)
db = SalaryDatabaseHelper.getDbInstance();
我用單身的輔助類和數據庫類:(都是通過輔助類訪問)
class MyDatabaseHelper extends SQLiteOpenHelper{
private static SalaryDatabaseHelper _instance = null;
private static SQLiteDatabase _dbInstance = null;
//singletons
public static synchronized SalaryDatabaseHelper getInstance(Context context)
{
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
if (_instance == null)
_instance = new SalaryDatabaseHelper(context.getApplicationContext());
return _instance;
}
public static synchronized SQLiteDatabase getDbInstance() {
if(_dbInstance == null)
_dbInstance = _instance.getWritableDatabase();
return _dbInstance;
}
...
什麼是_db?什麼是_databaseHelper?這些常規或靜態字段?這個異常在哪裏被提出? – CommonsWare
我加了一些代碼 – Pilpel