I am developing a android app work with the firebase database , when the user add item to the database the app display it at the Realtime and that what I want , but the problem it is that same item show more than one time in the RecyclerView this is the code that I try
data = new ArrayList<>(); DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("workers"); myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { e_iv.setVisibility(View.GONE); e_tv.setVisibility(View.GONE); rv_all.setVisibility(View.VISIBLE); for (DataSnapshot ds : snapshot.getChildren()) { for (DataSnapshot d : ds.getChildren()) { data.add(d.getValue(work.class)); } } mAdapter = new aAdapter(data); rv_all.setAdapter(allGamesAdapter); mAdapter.notifyDataSetChanged(); }
But it does not solve it ,and a side note when I go out from the app and enter again it is works perfectly and show the items without repeat anyone ,How can I solve that ?
Advertisement
Answer
What happening is the ArrayList is getting data added every time listener returns the data. To remove duplicacy just clear the arrayllist inside the onDataChange() function
data = new ArrayList<>(); DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("workers"); myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { data.clear(); e_iv.setVisibility(View.GONE); e_tv.setVisibility(View.GONE); rv_all.setVisibility(View.VISIBLE); for (DataSnapshot ds : snapshot.getChildren()) { for (DataSnapshot d : ds.getChildren()) { data.add(d.getValue(work.class)); } } mAdapter = new aAdapter(data); rv_all.setAdapter(allGamesAdapter); mAdapter.notifyDataSetChanged(); }
Hope your bug is resolved.