Home > other >  Why is the recycler view has NullPointerException in fragment?
Why is the recycler view has NullPointerException in fragment?

Time:07-20

so here is the code for my recycler view adapter, which is located at onCreate:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    databaseReference = FirebaseDatabase.getInstance().getReference("profilUsaha")
    auth = FirebaseAuth.getInstance()
    uid = auth.currentUser?.uid.toString()

    daftar_pesan_recycler_view.adapter = adapter
    listenForLatestMessages()

    arguments?.let {
        param1 = it.getString(ARG_PARAM1)
        param2 = it.getString(ARG_PARAM2)
    }
}

But somehow, the following error appears:

2022-07-20 00:29:23.872 17032-17032/com.example.gesit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.gesit, PID: 17032
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
    at com.example.gesit.PesanFragment.onCreate(PesanFragment.kt:51)
    at androidx.fragment.app.Fragment.performCreate(Fragment.java:2981)
    at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:474)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1758)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701)
    at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:488)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

How to fix this issue? Thanks.

CodePudding user response:

onCreate() is too early in the fragment lifecycle, the fragment view has not yet been created.

You can move the view setup code such as setting recyclerview adapter to onViewCreated().

CodePudding user response:

Probably this is not the case but... As a general rule all initialization that need instance of the activity must be in onActivityCreated() (or the next methods in the Fragment lifecycle). Inside onCreateView() getActivity() is not guaranteed to return non-null value. In some scenarios it returns null.

So Make Sure your RecyclerView is not null.

  • Related