tim_d
tim_d

Reputation: 133

findViewByID returns null within FirestoreRecyclerAdapter

I'm trying to FirestoreRecyclerAdapter, and the data is loading and can be seen in the debugger just fine. However, when I try to set a TextView equal to some of the data it crashes because the the TextView is null.

When debugging it does first try to set the TextView using findViewById, but it fails and it is set to null.

I've seen suggestions of using onFinishInflate, but am unsure of where I can override that function in this scenario.

Debugging Session

public class PostAdapter extends FirestoreRecyclerAdapter<Post, PostAdapter.PostHolder> {

    public PostAdapter(@NonNull FirestoreRecyclerOptions<Post> options) {
        super(options);
    }

    @NonNull
    @Override
    public PostHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.post_layout,
                viewGroup, false);


        return new PostHolder(v);
    }

    class PostHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvPitch;

        public PostHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.etTitle);
            tvPitch = itemView.findViewById(R.id.etPitch);
        }

    }

    @Override
    protected void onBindViewHolder(@NonNull PostHolder holder, int position, @NonNull Post model) {
        holder.tvTitle.setText(model.title);
        holder.tvPitch.setText(model.pitch);
    }
}



_________________________________________________



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/tvPitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

Upvotes: 0

Views: 189

Answers (2)

Intsab Haider
Intsab Haider

Reputation: 3561

You are using wrong reference to TextView i.e

etTitle

while your XML shows tvTitle And Also the second textview is referring to wrong Id. So your code should be like this

 tvTitle = itemView.findViewById(R.id.tvTitle);
 tvPitch = itemView.findViewById(R.id.tvPitch);

Upvotes: 3

Abbas Jafari
Abbas Jafari

Reputation: 1643

Use this etPitch = itemView.findViewById(R.id.tvPitch); code.

Upvotes: 1

Related Questions