简体   繁体   中英

RecyclerView crashes with NullPointerException in Fragment

RecyclerView works normally when used in activity but when used in fragment it gives error as below

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
        at restaurant.menu.fragments.MealsFragment.onCreate(MealsFragment.java:42)

fragment_meals.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.MealsFragment">

    <!-- TODO: Update blank fragment layout -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvMeals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

MealsFragment.java

    public class MealsFragment extends Fragment {
     public MealsFragment() {
        // Required empty public constructor
    }
    RecyclerView recyclerView;
    itemAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayList<Items> ItemsList;
        ItemsList=  (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getActivity().getApplicationContext())
                .getAppDatabase()
                .getDao()
                .getItems("Meals");
        recyclerView = getActivity().findViewById(R.id.rvMeals);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity(),RecyclerView.VERTICAL,false);
        recyclerView.setLayoutManager(manager);
        adapter = new itemAdapter(getActivity().getApplicationContext(), ItemsList);
        recyclerView.setAdapter(adapter);

    }

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

As per the Fragment lifecycle guide , onCreate() is called before onCreateView . That means that your Fragment's view hasn't been created yet.

Instead, you want to move all of your code from onCreate() into onViewCreated() - that is the method that is called after onCreateView() and is where you can access your newly inflated views. Note that you cannot and should not be using getActivity().findViewById() - that finds views in your activity's layout, not in your fragment's layout:

public class MealsFragment extends Fragment {

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

    RecyclerView recyclerView;
    itemAdapter adapter;

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
                .getAppDatabase()
                .getDao()
                .getItems("Meals");
        recyclerView = view.findViewById(R.id.rvMeals);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(
            getContext(), RecyclerView.VERTICAL,false);
        recyclerView.setLayoutManager(manager);
        adapter = new itemAdapter(getContext(), ItemsList);
        recyclerView.setAdapter(adapter);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM