When click on listview , delete it and delete associated data with it in firebase

前端 未结 2 876
忘了有多久
忘了有多久 2021-01-23 16:26

Hello and thanks for help I have asked here how to Polpulate listview from firebase and thankfully Krishna Kishan solved my problem but now what I like to do is when I click on

2条回答
  •  自闭症患者
    2021-01-23 17:09

    You have to modify some code that is outside the snippet you posted.

    I guess your items are read from the database. When you read your "message" node you have to save keys as well as values. You can achieve this in a number of ways. e.g.

    final ArrayList keyList = new ArrayList<>();
    final ArrayList items = new ArrayList<>();
    myRef.getRoot().child("messages")
            .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot messages : dataSnapshot.getChildren()) {
                keyList.add(messages.getKey());
                items.add(messages.getValue(String.class));
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            /*handle errors*/
        }
    });
    

    Now you have both keys and values. Modify your OnClickListener this way:

    listi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            items.remove(position);
            adapt.notifyDataSetChanged();
            //new code below
            myRef.getRoot().child("message").child(keyList.get(position)).removeValue();
            keyList.remove(position);
        }
    });
    

    Obviously listi.setOnItemClickListener( ... ) should be called when both keyList and items are properly filled. Please notice that ValueEventListener is asynchronous.

提交回复
热议问题