在 RecyclerView 的自定义适配器中膨胀时获取 nullpointerexception

Get nullpointerexception while inflating in custom adapter of RecyclerView

这是我的适配器的 onCreateViewHolder :

    @Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    try
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);
    }
    catch (Exception e)
    {
        return  null ;
    }

}

这行抛出 NullPointException:

    LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);

我调试了函数,但没有任何内容为 null,所以我不明白是什么导致了问题?

请删除 try 块。如下图

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.faviorate_video_item, parent, false);
        return new ViewHolder(v);


}

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

仅供参考

Java try block is used to enclose the code that might throw an exception. So no need to create try-catch block here.

你可以试试

View viewOBJ = LayoutInflater.from(parent.getContext()).inflate(R.layout.faviorate_video_item, parent, false);
ViewHolder viewHolderOBJ = new ViewHolder(viewOBJ);
return viewHolderOBJ;

根据你的错误行我猜可能是:

  1. 您的项目布局
  2. 您的数据

如果其中之一(很可能是第一个)导致问题,您可能会在充气时遇到无关的错误。所以我建议先检查一下

我也 运行 遇到了这个问题,我的问题是在我的项目布局中我放置了 <View> 元素但没有大写 V 并且编译器没有抱怨

 <view
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />