如何使用setMultiChoiceItems解决CursorIndexOutOfBoundsException - Android

时间:2017-12-28 10:25:46

标签: android

我想要一个包含多项选项的alertDialog(来自我的数据库的项目),但是当我使用它时,我有这样的错误:" android.database.CursorIndexOutOfBoundsException:请求索引2,大小为2&#34 ;

我从db获取数据的代码:

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+TABLE_NAME_2,null);
    return res;
}

我的数据库:

public static final String TABLE_NAME_2 = "word_table";
public static final String COL1_1 = "ID";
public static final String COL1_2 = "NAME";
public static final String COL1_3 = "VALUE";
public static final String COL1_4 = "ISSELECTED";

db.execSQL("create table " + TABLE_NAME_2 +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,VALUE TEXT,ISSELECTED INTEGER)");

我的代码使用multichoiceit

Cursor res = db.getAllData();
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMultiChoiceItems(res,res.getString(3),res.getString(1),new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface parent, int position,
                            boolean checked) {

        }

    });
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.show();

错误消息(我的数据库中只有2条记录):

android.database.CursorIndexOutOfBoundsException: Index 2 requested, with a size of 2

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

if ( res.getCount() < 4 )
    return;

res.getString(3) // can safely be called now

但是我不明白你的代码,因为定义是

 public AlertDialog.Builder setMultiChoiceItems (Cursor cursor
   , String isCheckedColumn, String labelColumn
   , DialogInterface.OnMultiChoiceClickListener listener) 

我宁愿认为你会这样称呼:

 builder.setMultiChoiceItems(res, "0", "1", .....         
 builder.setMultiChoiceItems(res, "ischecked", "label", .....

正如您现在发布的那样

public static final String COL1_3 = "VALUE";
public static final String COL1_4 = "ISSELECTED";

应该是:

builder.setMultiChoiceItems(res, COL1_4, COL1_3, .....