首页 > 解决方案 > findViewByID 在 FirestoreRecyclerAdapter 中返回 null

问题描述

我正在尝试 FirestoreRecyclerAdapter,并且数据正在加载并且可以在调试器中看到就好了。但是,当我尝试将 TextView 设置为等于某些数据时,它会崩溃,因为 TextView 为空。

调试时,它首先尝试使用 findViewById 设置 TextView,但失败并设置为 null。

我已经看到使用 onFinishInflate 的建议,但不确定在这种情况下我可以在哪里覆盖该函数。

调试会话

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>

标签: javaandroidasynchronousandroid-recyclerviewgoogle-cloud-firestore

解决方案


您使用了对 TextView 的错误引用,即

标题

而您的 XML 显示 tvTitle 并且第二个 textview 指的是错误的 Id。所以你的代码应该是这样的

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

推荐阅读