简体   繁体   中英

Why the data retrieve from firebase increase everytime I click on another fragment?

In History fragment, the history list keep increasing with the same data when I click other fragment and then go to history again. I just want it to display once. Below are the codes that I have done for History fragment.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_history, container, false);

    ref = FirebaseDatabase.getInstance().getReference().child("Users").child("1234").child("Feedback");

    listViewName = (ListView) view.findViewById(R.id.listView);
    arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList);
    listViewName.setAdapter(arrayAdapter);

   ChildEventListener childEventListener = new ChildEventListener() {
       @Override
       public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
           arrayList.add(dataSnapshot.getValue(SurveyDetails.class).getActivity());
           arrayAdapter.notifyDataSetChanged();
                    }

       @Override
       public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

       }

       @Override
       public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
           SurveyDetails surveyDetails = dataSnapshot.getValue(SurveyDetails.class);
           String activity = surveyDetails.getActivity();
           arrayList.remove(activity);
           arrayAdapter.notifyDataSetChanged();
           listViewName.setAdapter(arrayAdapter);

       }

       @Override
       public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

       }

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

       }
   };
   ref.addChildEventListener(childEventListener);

I expect the listview to display the output once only. But want I get is multiple time with the same data. 在此处输入图片说明

I suggest to clear the array first before executing new data arraList.Clear()

This code will remove duplicate value in your listView

HashSet hs = new HashSet();
hs.addAll(demoArrayList); // demoArrayList= name of arrayList from which u want 
to remove duplicates 

demoArrayList.clear();
demoArrayList.addAll(hs);

Now since we remove duplicates you can set again the adapter

Just clear your arraylist before setting up your adapter.

arrayList.clear();    // Add this line.
arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList); 

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