如何删除IndexOutOfBoundsException:索引2无效,大小为2 ..当我单击该项目时

时间:2016-05-31 06:37:02

标签: android

我想在一个列表视图中添加两个列表。当我点击项目应用程序崩溃并显示Index Out of Bounds Exception时。怎么解决呢?

在一个模型类中组合两个模型类,然后使用

我的sqlite方法是..

      public List<Combine>getListbyId(String id) {

            db = getReadableDatabase();
            List<Combine> combineList = new ArrayList<Combine>();
            String SELECT_QUERY_Category = " SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_PARENT_ID + " = " + id;

            Log.e("fetch","fetchitem " +SELECT_QUERY_Category);
            Cursor cursor = db.rawQuery(SELECT_QUERY_Category, null);


        if (cursor.moveToFirst()) {
            do {
                Combine combine = new Combine();
                combine.setId(cursor.getInt(0));
                combine.setName(cursor.getString(1));
                combine.setType(0);

                combineList.add(combine);
            } while (cursor.moveToNext());

            cursor.close();

    }
            String SELECT_QUERY_ITEM = " SELECT * FROM " + TABLE_ITEM + " WHERE " + ITEM_CATEGORY_ID + " = " + id;
            Log.e("fetch","fetchitem " +SELECT_QUERY_ITEM);
            Cursor cursor1 = db.rawQuery(SELECT_QUERY_ITEM, null);

                if (cursor1.moveToFirst()) {
                    do {
                        Combine combine = new Combine();
                        combine.setId(cursor1.getInt(0));
                        combine.setName(cursor1.getString(1));
                        combine.setType(1);

                        combineList.add(combine);
                    } while (cursor1.moveToNext());

                    cursor1.close();
                }
                    db.close();



            return combineList;
        }

然后我在单击列表视图类别时调用此方法并获取类别ID。         从列表中获取cat id。

     int cat_id = UnsobergamesApplication.combine.get(position).getId();
    call method..
     List<Combine>combineList = handler.getListbyId(String.valueOf(cat_id));

    check type "0" for catgory and "1" for Item
    get type..
     int type = UnsobergamesApplication.combine.get(position).getType();
        if (type == 0){
     if(!combineList.isEmpty())
    {

set adapter in list..
     adapter = new ArrayAdapter(SubCategoryActivity.this,android.R.layout.simple_list_item_1,combineList);                                                                            

listView_Category.setAdapter(adapter);
check type 1 for item ..
    }else(type==1){
 some code here for item.. when type one is click go next screen and show details of item..
    }

但是类型1不起作用,当我单击项目时,给出索引超出范围的异常 请解决我的问题,请如何检查类型,如何给予条件,请帮助我..谢谢

1 个答案:

答案 0 :(得分:0)

更改您的代码
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        // do what you need with the cursor here
        Combine combine = new Combine();
        combine.setId(cursor.getInt(0));
        combine.setName(cursor.getString(1));
        combine.setType(0);

        combineList.add(combine);
    }