今天在做android項目的時候遇到了一個異常:
記錄一下解決方案,方便今後自我查詢,同時若還有其他解決方案,請夥伴們提出寶貴意見,一起學習。。。。。。
解決方案一:DBhelper類繼承SQLiteOpenHelper類。做一個靜態引用,確保在任何時候只存在一個DBhelper實例,代碼如下:
public class DBhelper extends SQLiteOpenHelper {
//數據庫名
private static final String DATABASE_NAME_STRING = "xxxxxx.db";
//數據庫版本
private static final int DATABASE_VERSION = 1;
private static DBhelper mDBhelper;
public static DBhelper getInstance(Context context){
if(null == mDBhelper){
mDBhelper = new DBhelper(context.getApplicationContext());
}
return mDBhelper;
}
public DBhelper(Context context){
super(context,DATABASE_NAME_STRING,null,DATABASE_VERSION);
}
。。。。。//數據庫的其他操作
}
在創建數據庫的activity或者自定義封裝類中通過調用getInstance()來得到DBhelper實例。
//在需要創建的java類中聲明
private DBhelper helper;
private SQLiteDatabase db;
//在需要創建的方法中調用
if(null == db){
helper = DBhelper.getInstance(context);
db = helper.getWritableDatabase();
}
解決方案二:
1、在DBhelper即Database Adapter中添加close函數
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
2、複寫activity的onDestroy函數,在onDestroy中關閉數據庫即可
@Override
protected void onDestroy() {
super.onDestroy();
if (helper != null) {
helper .close();
}
}
希望此兩個方案也能給遇到相同問題的夥伴提供一些思路,僅供參考。