【问题标题】:NullPointerException - Database locked issue while retrieving data from database and storing into an arrayNullPointerException - 从数据库中检索数据并存储到数组中时出现数据库锁定问题
【发布时间】:2013-09-19 10:34:18
【问题描述】:

我正在尝试从数据库中的 PersonDOB 列中检索日期列表(以字符串格式)。然后我遇到了数据库锁定问题。我已经为数据库声明了 open() 和 close() 方法。即使我收到这些错误。我无法理解,为什么我会收到此错误。 我读过一些类似的文章

Question - 1

Question - 2

不仅这些,我还尝试了其他问题和文章中给出的解决方案。但是我无法获得适合我的上下文的适当解决方案。 在我的整个代码中,我只使用了一次写入操作。因此,不存在数据损坏的问题。 这是我从数据库中获取数据的代码。

public String[] getDataInArray() { // get data for list and return in array form
        // TODO Auto-generated method stub
        SQLiteDatabase myDB;
        String[] return_columns;
         try {

              myDB=this.openDataBase();       
              String DOB = "PersonDOB";
            String[] columms = new String[]{ DOB };



            Cursor c = myDB.query("Persons", columms, null, null, null, null, null);

            int iDOB = c.getColumnIndex(DOB);

            int rowcount = 0;
              return_columns = new String[c.getCount()];
            for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
            {
                return_columns[rowcount] = c.getString(iDOB);
                rowcount = rowcount + 1;
            }



                  if(c != null)
                 {
                     myDB.close();
                     c.close();
                  }          


                  }catch(SQLException sqle){

                  throw sqle;

                  }
         for (int i = 0;i<return_columns.length;i++)
            {
                                     Log.v("DOB", return_columns[i]); //I am not
 getting this log message in the logcat.
            }
        return return_columns;
        }

我在 logcat 中收到以下错误 -

09-19 15:58:00.140: W/System.err(7115): java.lang.NullPointerException
09-19 15:58:00.140: W/System.err(7115):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
09-19 15:58:00.140: W/System.err(7115):     at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-19 15:58:00.200: W/System.err(7115):     at com.example.fromstart.adapter.open(adapter.java:30)
09-19 15:58:00.210: W/System.err(7115):     at com.example.fromstart.adapter.getDataInArray(adapter.java:222)

提前致谢。

【问题讨论】:

  • 不确定这是否能解决您的问题,但如果您的光标为空,则数据库永远不会关闭。尝试将 myDB.close() 移到 if(c !=null) 下方
  • 好的@UngureanuLiviu,我会试试的。

标签: java android mysql database sqlite


【解决方案1】:

关闭数据库myDB.close(); 不足以避免锁定。在关闭数据库之前或使用游标的操作完成时,您需要关闭用于database 操作的cursors。如果您使用Threads,请确保它们也必须正确关闭。

【讨论】:

  • 感谢@Avadhani Y 的回复,我现在也关闭了光标。请查看我更新的代码。但是我在日志中遇到了同样的错误。
  • @nki 关闭数据库后如何关闭游标?将c.close() 放在myDB.close() 之前
  • 我已经按照你说的做了更改。但也得到同样的错误。我在myDB.close(); 之前放置了c.close();。当时这对我有用。
  • 您知道出现此错误的其他原因吗?
  • 可能无法正确关闭threads、cursors、database objects,... 请参考此文档:sqlite.org/lockingv3.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多