ArrayIndexOutOfBoundsException /将arraylist从alertdialog传递给activity

时间:2014-11-18 10:37:52

标签: java android arraylist alertdialog indexoutofboundsexception

我有一个有多个选项的alertdialog,我将用户的选择存储在字符串的ArrayList上,我想将存储的arraylist传递给host活动(我将使用数组的元素来查询我的数据库)..

当我运行我的应用程序时,我得到一个ArrayIndexOutOfBoundsException(可能是索引是-1 ..),我不确定它是否是循环,或者我没有正确地从alertdialog传递arraylist ...

你能看看吗?这是我的功能:

    public void onOkay(ArrayList<String> selected) {
    StringBuilder stringBuilder = new StringBuilder();
    if (selected.size() != 0) {
        for (int i = 0; i < selected.size(); i++) {
            String categories = selected_items_array[selected.indexOf(i)];
            stringBuilder = stringBuilder.append(" " + categories);
        }
        Toast.makeText(this, "You have selected: "
                + stringBuilder.toString(), Toast.LENGTH_SHORT).show();
    }

}

logcat:

java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1
        at com.hichamridouane.smartshop.MainActivity.onOkay(MainActivity.java:164)
        at com.hichamridouane.smartshop.TimelineSettings$2.onClick(TimelineSettings.java:71)

here是我的dialogfragment类。 并且here是我的主持人活动。(正如我所说,我不确定我是否正确地将arraylist传递给主持人活动) 谢谢!

2 个答案:

答案 0 :(得分:0)

对我来说这看起来很奇怪,特别是在

String categories = selected_items_array[selected.indexOf(i)];

从JavaDocs关于 indexOf

Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
More formally, returns the lowest index <tt>i</tt> such that
<tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
or -1 if there is no such index.

因此,您尝试在 selected_items_array 中找到元素(Java中的名称不正确) 在第一次迭代中 i == 0 selected_items_array 没有这样的元素=&gt; indexOf 返回 -1 数组不能包含index = -1的元素,它从0开始。所以你有 ArrayIndexOutOfBoundsException

答案 1 :(得分:0)

问题解决了。不得不在我的活动和对话片段中使用整数的Arraylists。

这是我在DialogFragment课程中所做的:

public class TimelineSettings extends DialogFragment {
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
boolean[] itemsChecked = {false, false, false, false, false, false};


// this interface to communicate with the host activity.

public interface dialoglistener {
    public void onOkay(ArrayList<Integer> selected);
    public void onCancel();
}
dialoglistener mlistener;


//this function is to instantiate the dialoglistener

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mlistener = (dialoglistener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement dialogListener");
    }
}

我的多语录对话框:

    @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    for(int i=0;i<itemsChecked.length;i++){
        if(selected_categories.contains((String)String.valueOf(i)))
            itemsChecked[i]=true;
    }

    // Set the dialog title
    builder.setTitle("Choisissez vos paramètres")
            .setMultiChoiceItems(R.array.categories, itemsChecked,
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int indexselected,
                                            boolean isChecked) {
                            if (isChecked) {
                                // If the user checked the item, add it to the selected items
                                if(!selected_categories.contains(indexselected)){
                                    selected_categories.add(indexselected);
                                    itemsChecked[indexselected]=true;
                                }
                            } else if (selected_categories.contains(indexselected)) {
                                // Else, if the item is already in the array, remove it
                                selected_categories.remove(indexselected);
                                itemsChecked[indexselected]=false;
                            }
                        }
                    })
                    // Set the action buttons
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    mlistener.onOkay(selected_categories);
                }
            })
            .setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    mlistener.onCancel();
                }
            });
    return builder.create();
}

在我的主持人活动中,我实现了片段的界面:

    @Override
public void onCreate(Bundle savedInstanceState) {
    /* some fancy stuff */
    Resources res = getResources();
    selectedArray = res.getStringArray(R.array.categories);
}

获取所选项目(并在吐司上展示,仅用于测试):

    @Override
public void onOkay(ArrayList<Integer> selected) {
    StringBuilder stringBuilder = new StringBuilder();
    if (selected.size() != 0) {
        for (int i = 0; i < selected.size(); i++) {
            String categories = selectedArray[selected.get(i)];
            stringBuilder = stringBuilder.append(" " + categories);
        }
        Toast.makeText(this, "You have selected: "
                + stringBuilder.toString(), Toast.LENGTH_SHORT).show();
    }
}