Android Firebase ChildEventListener返回相同数据的多个副本

时间:2017-06-17 04:26:40

标签: android firebase firebase-realtime-database fragment

在片段中使用firebase addChildEventListener,用于在实时数据库中更改的recycleview中显示数据。但每次我从一个片段移动到另一个片段并使用addChildEventListener返回到片段时会添加多个侦听器,这会导致相同数据的重复副本。

公共类列表扩展Fragment {      ChildEventListener mChildEventListener;

private RecyclerView recyclerViewUsers;
private ArrayList<Team> listUsers;
public static recycleview_adapter usersRecyclerAdapter;
private SQLiteDBHelper databaseHelper;
private SQLiteDBHelper sqd;
 FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("teams");

public list() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sqd = new SQLiteDBHelper(getActivity());
    myRef = FirebaseDatabase.getInstance().getReference();
    // myRef.removeEventListener(childEventListener);
    if(mChildEventListener != null) {
        myRef.removeEventListener(mChildEventListener);
    }
    mChildEventListener =myRef.child("teams").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
            Team1 newPost = dataSnapshot.getValue(Team1.class);
            System.out.println("Name: " + newPost.name);
            System.out.println("Points: " + newPost.Points);
            System.out.println(" ID: " + dataSnapshot.getKey());

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
            Team1 newPost = dataSnapshot.getValue(Team1.class);
            System.out.println("Name: " + newPost.name);
            System.out.println("Points: " + newPost.Points);
            System.out.println("ID : " + dataSnapshot.getKey());
            sqd.InsertData(newPost.name,Integer.parseInt(newPost.Points));
            if(list.super.isVisible()) {
                initObjects();
            }


        }


        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {}

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });



}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_list, container, false);
    recyclerViewUsers = (RecyclerView) view.findViewById(R.id.recyclerViewUsers);


    initObjects();
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);


}

public void onDetach() {
    super.onDetach();
    if(mChildEventListener != null) {
        myRef.removeEventListener(mChildEventListener);
    }
}

private void initObjects() {
    listUsers = new ArrayList<>();
    usersRecyclerAdapter = new recycleview_adapter(listUsers);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    recyclerViewUsers.setLayoutManager(mLayoutManager);
    recyclerViewUsers.setItemAnimator(new DefaultItemAnimator());
    recyclerViewUsers.setHasFixedSize(false);
    recyclerViewUsers.setAdapter(usersRecyclerAdapter);
    databaseHelper = new SQLiteDBHelper(getActivity());
    //divider
    RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerViewUsers.getContext(),
            linearLayoutManager.getOrientation());
    recyclerViewUsers.addItemDecoration(dividerItemDecoration);
    //
    getDataFromSQLite();
}


private void getDataFromSQLite() {
    // AsyncTask is used that SQLite operation not blocks the UI Thread.
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            databaseHelper = new SQLiteDBHelper(getActivity());
            listUsers.clear();
            listUsers.addAll(databaseHelper.getAllUser());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            usersRecyclerAdapter.notifyDataSetChanged();
        }
    }.execute();
}

@Override
public void onPause() {
    super.onPause();

    if (mChildEventListener != null) {
        myRef.removeEventListener(mChildEventListener);
    }
}

}

2 个答案:

答案 0 :(得分:0)

尝试setAdapter(null)然后再次加载数据或saveState 片段

答案 1 :(得分:0)

确保在附加新侦听器之前删除先前的事件侦听器。

databaseRef.removeEventListener(childEventListener);

您可以在onDetach()方法

中删除侦听器
@Override
public void onDetach() {
    super.onDetach();
    databaseRef.removeEventListener(childEventListener);
}