I’m doing a recycler method in my android studio project but i have a problem.
Everytime i’m trying to findViewById
my application is crashing.
Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
And i don’t understand why because i’m creating my view in the good way.
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_carrito, container, false); return view; }
And i’m trying to continue with that
@Override public void onAttach(@NonNull Context context) { super.onAttach(context); ... Log.e("test : ",Integer.toString(R.id.recyclerBuy)); recyView = view.findViewById(R.id.recyclerBuy); /* recyView.setLayoutManager(new GridLayoutManager(getContext(),RecyclerView.VERTICAL)); recyView.setAdapter(buyAdapter); */ }
But i’m crashing at the line recyView = view.findViewById(R.id.recyclerBuy);
. My R.id.recyclerBuy is not empty.
And here is my RecyclerView
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".ui.carrito.CarritoFragment"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerBuy" android:layout_width="match_parent" android:layout_height="550dp" android:layout_marginBottom="88dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" /> ... </androidx.constraintlayout.widget.ConstraintLayout>
Anyone have a clue why i’m crashing everytime ?
Advertisement
Answer
This happens because onAttach()
callback is called before onCreateView()
.
The easiest way to fix the issue is placing the code where you finding your RecyclerView
in onCreateView()
. Something like:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_carrito, container, false); recyView = view.findViewById(R.id.recyclerBuy); // here you recyView won't be null return view; }
A good article about fragments lifecycle: https://medium.com/androiddevelopers/the-android-lifecycle-cheat-sheet-part-iii-fragments-afc87d4f37fd