Android 游标初始化 [英] Android Cursor initialization

查看:20
本文介绍了Android 游标初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计了一个数据库.这是我的代码:

I have designed a database. Here is my code:

  Cursor cursor =database.query(ColumnID.AGENT_TABLE,null,null,null,null,null,null);

        while (cursor.moveToNext()) {
            County county = new County();
            county.setId(cursor.getString(cursor
                    .getColumnIndex(ColumnID.ID)));
            county.setAgent_Name(cursor.getString(cursor
                    .getColumnIndex(ColumnID.AGENT_NAME)));
            county.setAddress_Line_1(cursor.getString(cursor
                    .getColumnIndex(ColumnID.ADDRESS_LINE_1)));


            countyList.add(county);
        }

不幸的是,我收到此错误:

Unfortunately, I'm getting this error:

 Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

参考:Android 游标初始化

推荐答案

我不确定您是否收到错误消息,因为数据表中没有记录,而您正尝试在空集上使用 moveToNext(),或者是因为您正在访问不存在的结果的查询.

I'm not sure if you're getting the error because there are no records in the datatable and you're trying to moveToNext() on an empty set, or if it is because you are accessing the query for results that aren't there.

如果是前者:错误似乎是因为游标中没有记录,当您尝试 moveToNext() 时,该记录不存在.它是空指针异常的 SQLite 版本(有点).

If its the former: The error seems to be because there are no records in the cursor, when you try to moveToNext() the record doesn't exist. Its the SQLite version of a null pointer exception (sort of).

相反,请尝试:

Cursor cursor =database.rawQuery("SELECT * FROM " + ColumnID.AGENT_TABLE);

cursor.moveToFirst();
//this checks to make sure you don't have an empty set
if(!cursor.isAfterLast())
{
    do{
        County county = new County();
        county.setId(cursor.getString(cursor
            .getColumnIndex(ColumnID.ID)));
        county.setAgent_Name(cursor.getString(cursor
            .getColumnIndex(ColumnID.AGENT_NAME)));
        county.setAddress_Line_1(cursor.getString(cursor
            .getColumnIndex(ColumnID.ADDRESS_LINE_1)));


        countyList.add(county);
    }while(cursor.moveToNext());
} else{
    Log.v("MyTag", "There are no countries in the data set");
}

这篇关于Android 游标初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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