[英]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. 我希望listview仅显示一次输出。 But want I get is multiple time with the same data. 但要我得到的是多次使用相同的数据。
I suggest to clear the array first before executing new data arraList.Clear()
我建议先清除数组,然后再执行新数据arraList.Clear()
This code will remove duplicate value in your listView 此代码将删除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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.