我一直得到这恼人的运行时错误几个小时,坠毁我的应用程序:什么时候应该关闭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