我想通过在列表视图项上使用longclick从firebase中删除数据

时间:2019-03-10 15:48:34

标签: android firebase listview firebase-realtime-database

在这里我添加了长按侦听器,并且我希望长按选择的项目在单击“是”按钮后从Firebase中删除,并且火也从arraylist中删除,但是在单击“是”后我的应用程序停止工作,请帮助我摆脱了这个问题

ListOfFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {



            final String deleteditem=(String) ListOfFiles.getItemAtPosition(position);

            final AlertDialog.Builder builder=new AlertDialog.Builder(FetchFiles.this);
            builder.setTitle("Do You Want To Delete File ..? ");

            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    try
                    {
                        mRef.child(ID).child(deleteditem).removeValue();

                    }
                    catch (Exception e)
                    {
                        Toast.makeText(FetchFiles.this, (CharSequence) e, Toast.LENGTH_SHORT).show();
                    }


                }
            });
            builder.show();

            arrayAdapter.remove(deleteditem);
            arrayAdapter.notifyDataSetChanged();
            return false;

        }
    });

1 个答案:

答案 0 :(得分:0)

尝试添加Value Event Listener而不是OnClick方法(类似方法(对我有用))

ValueEventListener deleteListItem = new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            Firebase Ref.removeValue();
                            Toast.makeText(class.this, "Item deleted...", Toast.LENGTH_SHORT).show();

                            arrayList.remove(position);
                            arrayAdapter.remove(arrayAdapter.getItem(position));
                            arrayAdapter.notifyDataSetChanged();
                        }//onDataChange

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }//OnCancelled
                    };
Firebase Ref.addListenerForSingleValueEvent(deleteListItem);
dialog.dismiss();
                }//OnClick
            }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }//OnClick
            });
            alert.show();
            return true;
        }//OnItemLongClick
    });