Recyclerview scroll position with Firebase

Asked

Viewed 120 times

2

I am listing data from Firebase in a RecyclerView, but when adding or removing data, the data is repeated in the list. I used the clear(); or lista.removeAll(lista); to clear before filling only the list is updated and back scroll position to start. Does anyone have an idea how to avoid this? Just follow 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);

1 answer

2


The problem is being in the method recyclerView.setAdapter(recyclerViewAdapterEscalas); the ideal would be to instantiate the Adapter and assign to the recyclerView only 1 time, 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’ve helped.

  • Guilherme Montanher thank you so much for answering my question you are the guy solved my problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.