Home > Net >  Items in a RecyclerView are getting the data of previous items
Items in a RecyclerView are getting the data of previous items

Time:02-14

The application has a database with items that have columns of locations marked as integers which are displayed in a RecyclerView.

If any of the integers in the database columns is a zero, then the integer should not be displayed and to accomplish that I added if statements to check through each of the received integers and if the received integer is a zero, then it shouldn't be displayed.

private int journeyPosition;
...

  @Override
    public void onBindViewHolder(@NonNull JourneyAdapter.JourneyViewHolder holder, int position) {
        journeyPosition = holder.getAdapterPosition();
        JourneyObject journeyObject = journeyObjectList.get(holder.getAdapterPosition());

        if (journeyObject.getLocation1() != 0){
            holder.location1.setText(Integer.toString(journeyObject.getLocation1()));
        }
        if (journeyObject.getLocation2() != 0) {
            holder.location2.setText(Integer.toString(journeyObject.getLocation2()));
        }
        if (journeyObject.getLocation3() != 0) {
            holder.location3.setText(Integer.toString(journeyObject.getLocation3()));
        }
        if (journeyObject.getLocation4() != 0) {
            holder.location4.setText(Integer.toString(journeyObject.getLocation4()));
        }
        if (journeyObject.getLocation5() != 0) {
            holder.location5.setText(Integer.toString(journeyObject.getLocation5()));
        }

At the moment the code works correctly if all the locations are anything bigger than a zero, but since some of the locations in some items are a zero, then those integers are gotten from the RecyclerView's other items that have a number bigger than zero present in the field.

I have not yet figured out why the data is received from the previous adapter positions. If anything is unclear, then please specify what.

Thanks

CodePudding user response:

Remember that it’s a recycler view. The views scrolling onto the screen may have already been used. When you bind the view, don’t just use if statements. Use if/else statements so you can clear old data if you want to show nothing.

And a tip, when you find yourself writing a bunch of code that looks copy-pasted like that, find a way to do it by iteration instead. Your code will be cleaner, more concise, easier to read, and less error prone.

  • Related