简体   繁体   English

从arraylist中删除项目

[英]Removing item from arraylist

I'm trying to make an AlertDialog that gives you the option to delete the item you clicked in a Listview. 我试图做一个AlertDialog,使您可以选择删除在Listview中单击的项目。 I get the AlertDialog with the 2 options, but when i click them the AlertDialog just closes and nothing happends. 我得到带有2个选项的AlertDialog,但是单击它们时,AlertDialog只是关闭而没有任何反应。 Code below, thanks ahead. 下面的代码,谢谢。
Also when i press the positive button (that should delete the item) and i press the item again the app crashes. 另外,当我按下肯定按钮(应该删除该项目),然后再次按下该项目时,应用程序崩溃。

private void registerClickCallBack() {
    ListNote = (ListView) findViewById(R.id.lv1);
    ListNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> paret, View viewClicked, final int position, long id) {

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Notitie verwijderen?")
                    .setCancelable(false)
                    .setPositiveButton("Ja", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            lv.remove(position);
                        }
                    })
                    .setNegativeButton("Nee", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();

            ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, lv);
            ListNote.setAdapter(adapter);
        }
    });
}` 

I already figured it out. 我已经知道了。 I forgot to edit the listview inside the onclick method. 我忘了在onclick方法中编辑列表视图。 so the arraylist was empty but the value was still in the listview. 因此arraylist为空,但该值仍在listview中。 I moved the arrayadapter and it works fine now. 我移动了arrayadapter,现在工作正常。

I am sure you are looking for arrayList.RemoveAt(index) 我确定您正在寻找arrayList.RemoveAt(index)

You are attempting to arrayList.Remove(Object) 您正在尝试arrayList.Remove(Object)

The object you are attempting to remove is an int named 'position' and it does not exist in your arrayList (lv) so won't throw an exception. 您尝试删除的对象是一个名为“ position”的int,它在arrayList(lv)中不存在,因此不会引发异常。

There is a difference between Removing an object At a specific index and removing a specific object. 删除特定索引处的对象和删除特定对象之间有区别。 Depends on the reference you are passing. 取决于您传递的参考。

edit: attempting clarification 编辑:尝试澄清

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM