在onBindViewHolder中使用setText时出现NullPointerException

时间:2018-03-24 20:12:19

标签: android-recyclerview nullpointerexception

我在实现recyclerview时在OnBindViewHolder()中使用setText()时得到NullPointerException。我调试了整个代码但没有得到解决方案。请解释为什么' holder.articleName'被抛出为null对象?

适配器类:

public class ArticleListAdapter extends RecyclerView.Adapter<ArticleItemViewHolder> {
    String[] articles = {
            "article1",
            "article2",
            "article3",
            "article4",
            "article5"
    };

    @NonNull
    @Override
    public ArticleItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_article_list, parent, false);
        return new ArticleItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ArticleItemViewHolder holder, final int position) {
        holder.articleName.setText(articles[position]);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ArticleListActivity.this, "Article Clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return articles.length;
    }
}

ViewHolder类:

import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

public class ArticleItemViewHolder extends RecyclerView.ViewHolder{

    TextView articleName;
    CardView cardView;

    public ArticleItemViewHolder(View itemView) {
        super(itemView);
        this.articleName = itemView.findViewById(R.id.articleName);
        this.cardView = itemView.findViewById(R.id.cardView);
    }
}

1 个答案:

答案 0 :(得分:0)

确保具有TextView articleName 的布局位于此处 R.layout.activity_article_list 引用的布局页面中,而不是其他任何布局页面!