简体   繁体   中英

How to delete duplicated items in Listview filled with objects from real-time database

I am fetching data from my database based on the userId then I insert the data in a listview and show it through a dialog.

The behavior I was waiting for is is that I will get all the swaps the user has created and insert them in the list so he can choose one of them. But the code only works fine if he has only one swap in the database as it appears normally. But if he has two swaps then the swaps inside the list will be multiplied in two.

And if it's three then the data will get repeated three times and so on. I don't know what is the flow in my code here and hope there is someone who can help me in this problem. how can I get rid of the duplicated items in the list?

 private void fetchChooseList() {

    DatabaseReference shiftSwapDb = FirebaseDatabase.getInstance().getReference().child("swaps").child("shift_swaps");

    final List<SwapDetails> swapBodyList = new ArrayList<>();
    Collections.reverse(swapBodyList);
    shiftProfileAdapter = new ShiftProfileAdapter(ProfileActivityShift.this, R.layout.shift_profile_list_item, swapBodyList);
    listView = chooseShiftProfileDialog.findViewById(R.id.listShiftProfileChooseDialog);
    listView.setAdapter(shiftProfileAdapter);

    shiftSwapDb.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            if (dataSnapshot.exists()) {
                SwapDetails swapDetails = dataSnapshot.getValue(SwapDetails.class);
                if (swapDetails.getSwapperID().equals(fromID)) {
                    shiftProfileAdapter.add(swapDetails);
                }
            }
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) { }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
        @Override
        public void onCancelled(DatabaseError databaseError) { }
    });


    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            progressBar_ShiftProfileChooseDialog.setVisibility(View.VISIBLE);
            listView.setVisibility(View.INVISIBLE);
            SwapDetails swapDetails = swapBodyList.get(adapterView.getCount() - i - 1);
            fromLoginID = swapDetails.getSwapperLoginID();
            fromImageUrl = swapDetails.getSwapperImageUrl();
            fromName = swapDetails.getSwapperName();
            fromPhone = swapDetails.getSwapperPhone();
            fromEmail = swapDetails.getSwapperEmail();
            fromCompanyBranch = swapDetails.getSwapperCompanyBranch();
            fromAccount = swapDetails.getSwapperAccount();
            fromShiftDate = swapDetails.getSwapShiftDate();
            fromShiftDay = swapDetails.getSwapperShiftDay();
            fromShiftTime = swapDetails.getSwapperShiftTime();
            fromPreferredShift = swapDetails.getSwapperPreferredShift();
            String child = fromID + fromShiftDay + fromShiftTime + fromPreferredShift + toID + toShiftDay + toShiftTime + toPreferredShift;
            shiftSwapRequestsDb = FirebaseDatabase.getInstance().getReference().child("Swap Requests").child("Shift Request")
                    .child(child);
            swapRequestShift = new SwapRequestShift(toID,
                    toLoginID,
                    toImageUrl,
                    toName,
                    toPhone,
                    toEmail,
                    toCompanyBranch,
                    toAccount,
                    toShiftDate,
                    toShiftDay,
                    toShiftTime,
                    toPreferredShift,
                    fromID,
                    fromLoginID,
                    fromImageUrl,
                    fromName,
                    fromPhone,
                    fromEmail,
                    fromCompanyBranch,
                    fromAccount,
                    fromShiftDate,
                    fromShiftDay,
                    fromShiftTime,
                    fromPreferredShift,
                    -1,
                    -1);
            shiftSwapRequestsDb.setValue(swapRequestShift)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            //set the request message
                            requestMessage = userName + "" + " wants to swap with your shift";

                            Map<String, Object> notificationMessage = new HashMap<>();
                            notificationMessage.put("message", requestMessage);
                            notificationMessage.put("from", currentUserId);

                            notificationDB.child(swapperID).push()
                                    .setValue(notificationMessage).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        progressBar.setVisibility(View.INVISIBLE);
                                    }
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(ProfileActivityShift.this, "Something went wrong", Toast.LENGTH_LONG).show();
                                    Log.e(LOG_TAG, "Failed to insert row for " + currentUserId);
                                }
                            });
                            Toast.makeText(ProfileActivityShift.this, "Notification sent", Toast.LENGTH_LONG).show();
                            progressBar_ShiftProfileChooseDialog.setVisibility(View.INVISIBLE);
                            listView.setVisibility(View.VISIBLE);
                            chooseShiftProfileDialog.dismiss();
                            shiftProfileDialog.dismiss();
                            progressBar.setVisibility(View.INVISIBLE);
                            textSentOrAcceptedRequest.setVisibility(View.VISIBLE);
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(ProfileActivityShift.this, e.getMessage(), Toast.LENGTH_LONG).show();
                    progressBar_ShiftProfileChooseDialog.setVisibility(View.INVISIBLE);
                    listView.setVisibility(View.VISIBLE);
                    chooseShiftProfileDialog.dismiss();
                    shiftProfileDialog.dismiss();
                    progressBar.setVisibility(View.INVISIBLE);
                    buttonSwapRequest.setVisibility(View.VISIBLE);
                }
            });
        }
    });

}

try this

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    if (dataSnapshot.exists()) {
        SwapDetails swapDetails = dataSnapshot.getValue(SwapDetails.class);
        if (swapDetails.getSwapperID().equals(fromID)) {
            swapBodyList.add(swapDetails);
            shiftProfileAdapter.notifyItemInserted(swapBodyList.length - 1);
        }
    }
}

Problem solved. the reason was that the if statement is adding the entire data in swapdetails object if it found a user ID then it found another one and added all of them again etc.

so just I have created bloolean inside the if statement and make it take true if it found swaper ID and then use the adapter outside the scope of the addChildEventListene.

 shiftSwapDb.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        if (dataSnapshot.exists()) {
            SwapDetails swapDetails = dataSnapshot.getValue(SwapDetails.class);
            if (swapDetails.getSwapperID().equals(fromID)) {

hasSwaperID = true;
            }
        }
    }

shiftProfileAdapter.add(swapDetails);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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