Reputation: 61
The problem is that my RecyclerView doesn't get updated unless I set a new adapter. Here's the code:
TransferLab transferLab = TransferLab.get(getActivity());
List<Transfer> transfers = transferLab.getTransfers();
if (mAdapter == null) {
mAdapter = new TransferAdapter(transfers);
mTransferRecyclerView.setAdapter(new TransferAdapter(transfers));
} else {
mAdapter.setTransfers(transfers);
mAdapter.notifyDataSetChanged();
}
As you see I get a new list and pass it into the adapter. But the RecyclerView doesn't change until I restart the app or replace the IF-section with the code below:
mAdapter = new TransferAdapter(transfers);
mTransferRecyclerView.setAdapter(new TransferAdapter(transfers));
Inside the adapter:
private class TransferAdapter extends RecyclerView.Adapter<TransferViewHolder> {
private List<Transfer> mTransfers;
public TransferAdapter(List<Transfer> transfers) {
mTransfers = transferList;
}
public void setTransfers(List<Transfer> transfers) {
mTransfers = transfers;
}
@NonNull
@Override
public TransferViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
return new TransferViewHolder(inflater, parent);
}
@Override
public void onBindViewHolder(@NonNull TransferViewHolder holder, int position) {
holder.bind(mTransfers.get(position));
}
@Override
public int getItemCount() {
return mTransfers.size();
}
}
Upvotes: 1
Views: 39
Reputation: 6703
You are not setting mAdapter
to your mTransferRecyclerView
but rather creating a new instance of TransferAdapter
and setting that instead. As a result, mAdapter
is not set to any RecyclerView and updating it does nothing.
Change this part of your code:
mTransferRecyclerView.setAdapter(new TransferAdapter(transfers));
to
mTransferRecyclerView.setAdapter(mAdapter);
P.S. I would actually suggest you to remove List<Transfer> transfers
from constructor of your TransferAdapter class and initialize your field private List<Transfer> mTransfers;
to empty list. Then after inflating views create an instance of adapter and set it to RecyclerView immediately. When data is ready later you can call your setTransfers
method and notify adapter.
Upvotes: 1
Reputation: 3180
I think it should be implemented this way
public void setTransfers(List<Transfer> transfers) {
mTransfers.clear() //clear the old data
Collections.copy(mTransfers, transfers) //copy the new data to old empty list
}
Upvotes: 0