【问题标题】:Android Cursor Illegal state exception crashAndroid光标非法状态异常崩溃
【发布时间】:2019-01-10 12:26:21
【问题描述】:

我的一段 android 代码有一些问题,崩溃似乎发生在这里 c.moveToFirst()。我试图得到一个计数,如果游标结果大于0;然后执行该代码,但这无济于事。

我无法在我的应用程序上重现此错误(我尝试了多种方案),但是,通过 Google 开发控制台,我看到使用我的应用程序的其他人收到此错误。

提前致谢

崩溃错误:

java.lang.IllegalStateException: 
  at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked (SQLiteConnectionPool.java:1198)
  at android.database.sqlite.SQLiteConnectionPool.waitForConnection (SQLiteConnectionPool.java:808)
  at android.database.sqlite.SQLiteConnectionPool.acquireConnection (SQLiteConnectionPool.java:534)
  at android.database.sqlite.SQLiteSession.acquireConnection (SQLiteSession.java:904)
  at android.database.sqlite.SQLiteSession.executeForCursorWindow (SQLiteSession.java:834)
  at android.database.sqlite.SQLiteQuery.fillWindow (SQLiteQuery.java:62)
  at android.database.sqlite.SQLiteCursor.fillWindow (SQLiteCursor.java:152)
  at android.database.sqlite.SQLiteCursor.getCount (SQLiteCursor.java:141)
  at com.andre3.wzlimitdistraction.dao.Dao.read (Dao.java:101)
  at com.andre3.wzlimitdistraction.utils.MonitorService$2.run (MonitorService.java:201)
  at java.util.TimerThread.mainLoop (Timer.java:555)
  at java.util.TimerThread.run (Timer.java:505)

导致它的代码:

    ArrayList<UserApps> arr = new ArrayList<UserApps>();

    int profileId = 0;
    SQLiteDatabase getDb = db.getReadableDatabase();

    if(getDb.isOpen()) {

        String[] columns = {Dbinfo.app.toString(), Dbinfo.app_name.toString(), Dbinfo.start_duration.toString(), Dbinfo.active_duration.toString(), Dbinfo.start_time.toString(), Dbinfo.profile_id.toString()};

        String selection = Dbinfo.app.toString() + " =? and " + Dbinfo.profile_id.toString() + " <=?";
        String[] selectionArgs = {id, String.valueOf(profileId)};
        Cursor c = getDb.query("user_apps", columns, selection, selectionArgs, null, null, null);

        if((c.getCount() > 0) && (c !=null)) {

            if (c.moveToFirst()) {

                do {
                    UserApps form = new UserApps();

                    form.setPkg(c.getString(c.getColumnIndex(Dbinfo.app.toString())));
                    form.setName(c.getString(c.getColumnIndex(Dbinfo.app_name.toString())));

                    arr.add(form);
                } while (c.moveToNext());
            }
        }

        getDb.close();
        c.close();

    }
    return arr;

【问题讨论】:

  • 堆栈跟踪有getCount(),但您发布的代码没有。这不是导致崩溃的代码。
  • @laalto - 我确实说过“我已经尝试获取计数,如果游标结果大于 0,则执行代码,但这无济于事。”澄清一下,在 if 块中使用 getCount() 之前,崩溃发生在 c.moveToFirst() - 我更新了代码以反映我所拥有的。谢谢
  • 好的 - getDb 是什么,你是如何初始化/处理它的?
  • @laalto - 我已经用完整的代码块更新了我的帖子。感谢您的回复。
  • 不一定是问题,但您应该先关闭游标,然后再关闭数据库。

标签: android sqlite cursor


【解决方案1】:

这可能是因为 getColumnIndex 找不到您指定的列。你可以参考这个Question

【讨论】:

  • 事实并非如此。所有列名都有效。正如我所说,代码在我的设备上运行良好,只有少数其他使用我的应用程序的人遇到了这些崩溃。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 2023-03-23
相关资源
最近更新 更多