RecyclerView scroll position with Firebase

2

I'm listing Firebase data in a RecyclerView , but when adding data or removing, the data repeats in the list. I used clear(); or lista.removeAll(lista); to clear before filling only that the list is updated and returns the scroll position to the beginning. Does anyone have an idea how to avoid this?  Here's my code:

ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //
        Escala.removeAll(Escala);
        for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

            ModelEscala model = singleSnapshot.getValue(ModelEscala.class);
            Escala.add(model);
            recyclerViewAdapterEscalas = new RecyclerViewAdapterEscalas(getActivity(), Escala, mImageLoader);
            recyclerViewAdapterEscalas.notifyDataSetChanged();

            recyclerView.setAdapter(recyclerViewAdapterEscalas);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
};

mDataBase.addValueEventListener(listener);
    
asked by anonymous 11.12.2017 / 22:27

1 answer

2

The problem is being in the recyclerView.setAdapter(recyclerViewAdapterEscalas); method, it would be ideal to instantiate the adapter and assign it to the recyclerView only once, to update the data you just need to manipulate your ArrayList and notify the adapter ( recyclerViewAdapterEscalas.notifyDataSetChanged(); )

Example:

recyclerViewAdapterEscalas = new RecyclerViewAdapterEscalas(getActivity(), Escala, mImageLoader);
recyclerView.setAdapter(recyclerViewAdapterEscalas);

ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {       
        Escala.removeAll(Escala);
        for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

            ModelEscala model = singleSnapshot.getValue(ModelEscala.class);
            Escala.add(model);
            recyclerViewAdapterEscalas.notifyDataSetChanged();            
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
};

mDataBase.addValueEventListener(listener);

Try this way, I hope I have helped.

    
12.12.2017 / 11:06