how to use onBindViewHolder with multiple items in android RecyclerView

Ahmed Wagdi :

I'm Creating a RecyclerView with CardView's inside of it, Every card has title, description, and an image. Using onBindViewHolder allows me to only add a title, and I can't get it to add other items. Here is how I tried to do it.

This is my Adapter:

public class userDressAdapter extends RecyclerView.Adapter<userDressAdapter.ViewHolder> {

    private LayoutInflater layoutInflater;
    private List<String> data;
    private Object ViewGroup;

    userDressAdapter(Context context, List<String> data) {
        this.layoutInflater = LayoutInflater.from(context);
        this.data = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.dress_recycler_view, (android.view.ViewGroup) ViewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        String title = data.get(position);
        ViewHolder.dressTitle.setText(title);
        ViewHolder.dressDescription.setText(title);


    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        static TextView dressTitle;
        static TextView dressDescription;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            dressTitle = itemView.findViewById(R.id.userDressTitleText);
            dressDescription = itemView.findViewById(R.id.userDressDescriptionText);
        }
    }
}

And I am using this as the main Adapter for my view, and here is how i call it from the main Java class:

public class UserDressView extends AppCompatActivity {
    private static final String TAG = "UserDressView";
    RecyclerView recyclerView;
    com.innoventiq.fostania.userDressAdapter userDressAdapter;
    ArrayList<String> items;
    ArrayList<String> description;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_dress_view);
        items = new ArrayList<>();
        description = new ArrayList<>();
        ReadDressData();
    }

    public void AddDressToList(String theData) {
        items.add(theData);
        recyclerView = findViewById(R.id.userDressRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        userDressAdapter = new userDressAdapter(this, items);
        recyclerView.setAdapter(userDressAdapter);
    }

    public void AddDressDescriptionToList(String theData) {
        description.add(theData);
        recyclerView = findViewById(R.id.userDressRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        userDressAdapter = new userDressAdapter(this, description);
        recyclerView.setAdapter(userDressAdapter);
    }

    public void ReadDressData() {
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        db.collection("dress")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                                AddDressToList(String.valueOf(document.getData().get("title")));
                                AddDressDescriptionToList(String.valueOf(document.getData().get("description")));
                            }
                        } else {
                            Log.w(TAG, "Error getting documents.", task.getException());
                        }
                    }
                });
    }
}

As I'm very new to android studio and JAVA I didn't find a guide for this. I added 2 functions that adds to difrrent lists to the Adapter , but the result is a mess. Texts are being added everywhere and items are dupliacated.

Martin Zeitler :

Add items to ArrayList<Dress> and then set the DressAdapter only once.

And with @Bindable fields, one can data-bind the card-views.

class Dress extends BaseObservable {

    private String title;

    private String desc;

    /** Constructor */
    public Dress() {}

    /** Constructor, new instance from Firestore {@link QueryDocumentSnapshot} */
    public Dress(@NonNull QueryDocumentSnapshot snapshot) {
        this.fromSnapshot(snapshot);
    }

    public void setTitle(@NonNull String value) {
        boolean changed = !TextUtils.equals(this.title, value);
        if(changed) {
            this.title = value;
            notifyPropertyChanged(BR.title);
        }
    }

    public void setDesc(@NonNull String value) {
        boolean changed = !TextUtils.equals(this.desc, value);
        if(changed) {
            this.desc = value;
            notifyPropertyChanged(BR.desc);
        }
    }

    @Bindable
    public String getTitle() {
        return this.title;
    }

    @Bindable
    public String getDesc() {
        return this.desc;
    }

    public void fromSnapshot(@NonNull QueryDocumentSnapshot snapshot) {
        this.setTitle(String.valueOf(snapshot.getData().get("title")));
        this.setDesc(String.valueOf(snapshot.getData().get("description")));
    }
}

to add the items:

ArrayList<Dress> mItems = new ArrayList<>();
...

if (task.isSuccessful()) {
    for (QueryDocumentSnapshot snapshot : Objects.requireNonNull(task.getResult())) {
        mItems.add(new Dress(snapshot));                
    }
    recyclerView.setAdapter(new dressAdapter(mItems));
 }

onBindViewHolder() is being called for each item.

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable name="dress" type="com.acme.model.Dress"/>
    </data>

    <com.google.android.material.card.MaterialCardView
        android:id="@+id/cardview"
        style="@style/Widget.MaterialComponents.CardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:color="?android:colorControlHighlight"
                android:fontFamily="sans-serif-medium"
                android:text="@{dress.title}"
                android:textColor="#000000"
                android:textSize="16sp"
                tools:text="@string/tools_dress_title"/>

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/desc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:color="?android:colorControlHighlight"
                android:fontFamily="sans-serif-medium"
                android:text="@{dress.desc}"
                android:textColor="#000000"
                android:textSize="16sp"
                tools:text="@string/tools_dress_desc"/>

        </androidx.appcompat.widget.LinearLayoutCompat>

    </com.google.android.material.card.MaterialCardView>

</layout>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324317&siteId=1