Android RecyclerView:尝试在空对象引用上调用虚方法'void androidx.recyclerview.widget.RecyclerView.setAdapter()

Android RecyclerView: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter() on a null object reference

我尝试在具有自定义布局的 Fragment 上创建 RecyclerView,因此我使用了一个适配器,但是,当我尝试设置适配器时,出现了这些错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference

网上试了一些解决方法,大家建议在OnViewCreated里面找recyclerview试试。但是我的代码仍然无法在布局文件中找到recyclerview。

这是我的fragment_hadiah.xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HadiahFragment"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:padding="20dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_video"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="x Dopa Eggs"
                android:textSize="20sp"
                android:textStyle="bold"
                android:layout_marginStart="10dp"/>
        </LinearLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tukarkan pointmu"/>
    </LinearLayout>

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:paddingVertical="10dp">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="GOPAY"
                android:layout_marginLeft="20dp"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="OVO"
                android:layout_marginLeft="20dp"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="DANA"
                android:layout_marginLeft="20dp"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Coming Soon"
                android:layout_marginLeft="20dp"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Coming Soon"
                android:layout_marginLeft="20dp"/>

        </LinearLayout>
    </HorizontalScrollView>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/hadiahRecylerView"/>

</LinearLayout>

这是我的HadiahFragment.javaclass

package com.dopami.projecthatchedeggs;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.dopami.projecthatchedeggs.adapter.HadiahItemAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HadiahFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HadiahFragment extends Fragment {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    RecyclerView hadiahRecyclerView;

    public HadiahFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HadiahFragment.
     */
    public static HadiahFragment newInstance(String param1, String param2) {
        HadiahFragment fragment = new HadiahFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_beranda, container, false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        List<String> itemList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            itemList.add(String.valueOf(i));
        }

        Toast.makeText((HomeActivity) getActivity(), "OK", Toast.LENGTH_SHORT).show();

        hadiahRecyclerView = view.findViewById(R.id.hadiahRecylerView);
        HadiahItemAdapter itemAdapter = new HadiahItemAdapter(itemList, (HomeActivity) getActivity());
        GridLayoutManager gridLayoutManager = new GridLayoutManager((HomeActivity)getActivity(), 2);
        hadiahRecyclerView.setAdapter(itemAdapter);
        hadiahRecyclerView.setLayoutManager(gridLayoutManager);
    }
}

这是我的HadiahItemAdapter.javaClass

package com.dopami.projecthatchedeggs.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.dopami.projecthatchedeggs.R;

import java.util.List;

public class HadiahItemAdapter extends RecyclerView.Adapter<HadiahItemAdapter.ItemViewHolder>{

    private List<String> mItemList;
    private Context mContext;

    public HadiahItemAdapter(List<String> mItemList, Context mContext) {
        this.mItemList = mItemList;
        this.mContext = mContext;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        String item = mItemList.get(position);
        holder.textView.setText(item);
    }

    @Override
    public int getItemCount() {
        return mItemList.size();
    }

    class ItemViewHolder extends RecyclerView.ViewHolder{

        private CardView cardView;
        private TextView textView;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);

            cardView = itemView.findViewById(R.id.hadiahCardView);
            textView = itemView.findViewById(R.id.hadiahCardTextView);
        }
    }
}

期待大佬们的解答,感谢帮助...

您的片段像这样膨胀 XML:

View view =  inflater.inflate(R.layout.fragment_beranda, container, false);

R.layout.fragment_beranda 不是您想要的布局(或共享 fragment_hadiah.xml)。

因此在onViewCreated

hadiahRecyclerView = view.findViewById(R.id.hadiahRecylerView);
HadiahItemAdapter itemAdapter = new HadiahItemAdapter(itemList, (HomeActivity) getActivity());
GridLayoutManager gridLayoutManager = new GridLayoutManager((HomeActivity)getActivity(), 2);
hadiahRecyclerView.setAdapter(itemAdapter);

hadiahRecyclerView 在 XML 文件中不存在,因此变量 hadiahRecyclerView 为 null

意义

hadiahRecyclerView.setAdapter(itemAdapter);

此行因 NullPointerException 而崩溃

您分享的堆栈跟踪错误正是这样说的:

java.lang.NullPointerException: Attempt to invoke virtual method

'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)'

on a null object reference