java - findViewByID 在 FirestoreRecyclerAdapter 中返回 null

标签 java android asynchronous android-recyclerview google-cloud-firestore

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

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

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

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>

最佳答案

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

etTitle

当您的 XML 显示 tvTitle 时 另外,第二个 TextView 引用了错误的 ID。所以你的代码应该是这样的

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

关于java - findViewByID 在 FirestoreRecyclerAdapter 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673160/

相关文章:

android - 如何混合使用绝对大小和相对大小?

java - JPA LinkedHashMap 注释

Java Clipboard on Linux (text only),有的程序可以读,有的不能,为什么

android - 如何移除微调器中的分隔线?

android - 以编程方式在 Android 中打开 CSV 文件

安卓位置 : simple one-time GPS fetch using AsyncTask

WCF - AsyncPattern=true 或 IsOneWay=true

java - Lombok @SuperBuilder 没有初始化我的类对象

java - 如何使用 Maven 更改版本的第四位数字?

validation - Angular2 模板驱动的异步验证器