android SQLite :close() was never explicitly called on database 'XXXXXX'

来源:互联网 发布:windows ping 编辑:程序博客网 时间:2024/06/06 05:16

今天在做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();        }    }

希望此两个方案也能给遇到相同问题的伙伴提供一些思路,仅供参考。

0 0
原创粉丝点击