无法防止SQLiteConnection对象泄漏 [英] Unable to prevent SQLiteConnection object leakage

查看:74
本文介绍了无法防止SQLiteConnection对象泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Android应用中,我有一些使用SQLite的数据库事务,但是尽管尝试了许多防止泄漏的方法,但我还是遇到了SQLiteConnection对象泄漏.我几乎已经尝试了互联网上的每件事,例如关闭数据库,关闭游标或结束事务.以下是android studio中的警告.

In my Android app, I have some Database transaction using SQLite but I am getting SQLiteConnection object leakage despite trying many ways to prevent the leak. I have almost tried each and every thing in the internet like closing the db, closing the cursor, or ending the transaction. Below is the warning in android studio.

数据库'/data/user/0/com.example.myapp/databases/myapp.dbnotes.db'的SQLiteConnection对象泄漏了!请修复您的应用程序,以正确结束正在进行的事务,并在不再需要数据库时将其关闭.

A SQLiteConnection object for database '/data/user/0/com.example.myapp/databases/myapp.dbnotes.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

有时通过关闭数据库或关闭我用来获取错误的游标-尝试重新打开一个已经关闭的对象.... .我不是Android的专业人士,我想自己学习,所以您能帮我吗.我已经发布了以下代码:

Sometimes by closing the db or closing the cursor I used to get error - Attempt to reopen an already-closed object ..... I am not pro in Android, I am trying to learn by my own self , so could you help me. I have posted the codes below:

  • 在DBHelper类内部

  • Inside the DBHelper class

  public class DBHelper extends SQLiteOpenHelper {

    ...
      public static DBHelper getInstance(Context ctx) {

      if (mInstance == null) {
        mInstance = new DBHelper(ctx.getApplicationContext());
       }
       return mInstance;
     }

     private DBHelper(Context context) {
       super(context, DB_NAME, null, 1);
       this.context = context;
       DB_PATH = context.getDatabasePath(DB_NAME).getPath();
    }

   ...

   private Cursor getData(String Query) {
      String myPath = DB_PATH + DB_NAME;
      Cursor c = null;
     try {
          db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
          c = db.rawQuery(Query, null);
        } catch (Exception e) {
          e.printStackTrace();
         }
      return c;
     }

   private void dml(String Query) {
      String myPath = DB_PATH + DB_NAME;
      if (db == null)
        db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
      try {
         db.execSQL(Query);
      } catch (Exception e) {
         e.printStackTrace();
      }
    }




  //Methods to perform different db transaction

  public void addToSubject(ItemSubject itemSubject) {
   if (checkSuggested(itemSubject.getId())) {
     dml("delete from " + TABLE_SUBJECT + " where id = '" + itemSubject.getId() + "'");
   }
   String insert = "insert into TABLE_SUBJECT .....";
   dml(insert);
 }

 public void cleartable_subject() {
   String delete = "delete from " + TABLE_SUBJECT;
   dml(delete);
 }

public long subject_size() {
   if (db == null) {
     db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
   }
   try {
     long count = DatabaseUtils.queryNumEntries(db, TABLE_SUBJECT);
     return count;
   } catch (Exception e) {
     e.printStackTrace();
     return 0;
  }
 }

 private Boolean checkSubject(String id) {
   String select = "select * from " + TABLE_SUBJECT + " where id = '" + id + "'";
   Cursor cursor = getData(select);
   return cursor != null && cursor.getCount() > 0;
 }

 public ArrayList<ItemSubject> loadDataSubject() {
    ArrayList<ItemSubject> arrayList = new ArrayList<>();
    String select = "select * from " + TABLE_SUBJECT;
    Cursor cursor = getData(select);
    if (cursor != null && cursor.getCount() > 0) {
     cursor.moveToFirst();
     for (int i = 0; i < cursor.getCount(); i++) {
         String id = cursor.getString(cursor.getColumnIndex(TAG_ID));
         String course = cursor.getString(cursor.getColumnIndex(TAG_COURSE_NAME));
         ....
         ItemSubject objItem = new ItemSubject(id, courseId,...);
         arrayList.add(objItem);
         cursor.moveToNext();
     }
     cursor.close();
    }
    return arrayList;
   }

   //There are more similar methods for other tables

我正在片段和活动之类的内部访问这些方法

I am accessing these methods inside fragments and activities like

     dbHelper = DBHelper.getInstance(getActivity());

     if ((dbHelper.subject_size() >= 1){
      dbHelper.cleartable_subject();
      for (int i = 0; i < arrayListSubject.size(); i++) {
                dbHelper.addToSubject(arrayListSubject.get(i));
            }
            arrayListSubject = dbHelper.loadDataSubject();
     }

很抱歉,很长一段代码,但我认为一切都是必要的.你能帮我吗?

Sorry for the long section of codes, but I thought everything will be necessary. Could you please help me?

推荐答案

您说您在网上调查了许多问题,但您绝对没有调查.从字面上看,它花了5分钟时间进行搜索.

You say you looked into many questions online, but you definitely didn't look into this or this. It literally cropped up 5 minutes into searching.

无论如何,如果我是您,要解决此问题,请在关闭连接时包含一个 finally 子句.这意味着您将把数据库助手声明为静态实例变量,并使用Abstract Factory模式来保证单例属性.

Anyways, if I were you, to resolve this issue, I would include a finally clause when closing the connection. This means that you would be declaring your database helper as a static instance variable and use the Abstract Factory pattern to guarantee the singleton property.

您的警告之所以发生,是因为您不能确保在任何给定时间仅存在一个 DatabaseHelper .如果 mInstance 对象尚未初始化,则将创建一个.如果已经创建了一个,则将其简单地返回.

Your warning is happening because you are not ensuring that only one DatabaseHelper will ever exist at any given time. If the mInstance object has not been initialized, one will be created. If one has already been created then it will simply be returned.

这是代码:

public ArrayList<ItemSubject> loadDataSubject() {
    ArrayList<ItemSubject> arrayList = new ArrayList<>();
    String select = "select * from " + TABLE_SUBJECT;
    Cursor cursor = getData(select);
    
    
    if (cursor != null && cursor.getCount() > 0) {
    try {
        cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                String id = cursor.getString(cursor.getColumnIndex(TAG_ID));
                String course = cursor.getString(cursor.getColumnIndex(TAG_COURSE_NAME));
         ....
                ItemSubject objItem = new ItemSubject(id, courseId,...);
                arrayList.add(objItem);
                cursor.moveToNext();
           }
       finally {
           if (cursor != null)
           cursor.close();
       }
   }
   return arrayList;
}    

但是,由于您说的是,我对您的问题的唯一贡献(在其他帖子中已经得到回答)是改善您的基础英语水平,因此,我不确定您是否可以接受此答案.

But since you say that my only contribution to your question (which had already been answered in other posts) is that of refining your lack of elementary English, then I am not that sure if you can accept this as an adequate answer.

这篇关于无法防止SQLiteConnection对象泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆