【问题标题】:Android Studio - Cursor.getString() throwing exceptionAndroid Studio - Cursor.getString() 抛出异常
【发布时间】:2016-02-08 19:46:25
【问题描述】:

我是 Android Studio 的新手,这是我第一个使用数据库连接的应用程序,所以我可能只是从根本上误解了光标的工作原理。

我正在查询我的数据库,测试表明查询成功,特别是 getCount() 方法返回 2 作为游标对象包含的行数。但是,当我调用 getString() 方法时,它会抛出异常而不是返回列数据。

此代码可能有任何问题立即弹出?

    public void GetFacts(View v) {

    Cursor cursor = database.query(ExternalDbOpenHelper.TABLE_NAME,
            null, "valueRange = 'MEDIUM'", null, null, null, null);

    // Log number of rows from query
    Log.d("CursorTest", "Row count: " + cursor.getCount());

    try {
        // get data from "factName" column of database
        String columnName = cursor.getColumnName(0);
        Log.d("CursorTest", "Column Name: " + columnName);

        String data = cursor.getString(cursor.getColumnIndex(columnName));

    } catch(Exception e) {
        // Log exception thrown
        Log.d("CursorTest", "Error getting data: " + e.getMessage());

    }
}

日志给了我以下信息:

D/CursorTest:行数:2

D/CursorTest:列名:factName

D/CursorTest:获取数据时出错:请求索引 -1,大小为 2

【问题讨论】:

  • 在询问有关异常的问题或记录异常时,请务必报告异常的类型,例如 CursorIndexOutOfBoundsException,而不仅仅是异常的消息。这是找出问题所在的最关键信息。您可以通过将异常(您的 e 参数)作为第三个参数添加到 Log.d() 调用中轻松找到它。

标签: android database sqlite android-studio cursor


【解决方案1】:

尝试将光标移动到第一个例子的第一个位置

cursor.moveToPosition(0);

【讨论】:

  • 我投了赞成票,但他们不会在我达到 15 个代表之前显示我的反馈。
【解决方案2】:

您的光标在索引 -1 处初始化。您需要调用moveToNext()moveToPosition(int) 将其设置为其中包含数据的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2012-09-30
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多