Get Crashes Can't access the Fragment View's LifecycleOwner when getView()
Closed this issue · 9 comments
Get crashes like this even when i already check if lifecycle at least in STARTED
Fatal Exception: java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()
at androidx.fragment.app.Fragment.getViewLifecycleOwner(Fragment.java:361)
at android.view.View.performClick(View.java:7297)
at android.view.View.performClickInternal(View.java:7274)
at android.view.View.access$3600(View.java:819)
at android.view.View$PerformClick.run(View.java:28023)
at android.os.Handler.handleCallback(Handler.java:914)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:225)
at android.app.ActivityThread.main(ActivityThread.java:7564)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Hi @JosephSanjaya
You should access ViewBinding property after onCreateView until onDestroyView.
The problem is i'm not even trigger the onClick event, I'm assigned it on DataBinding as variable "listener" at onViewCreated which mean it safe right?.
May you post some lines of code ?
Fragment
class SampleFragment :Fragment(R.layout.sample_layout), View.OnClickListener {
private val mBinding by viewBinding(SampleLayoutBinding::bind)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mBinding.listener = this
}
override fun onClick(view: View?) {
if(viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
when(view) {
mBinding.sampleButton -> sampleFunction.invoke()
}
}
super.onClick(view)
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="listener"
type="android.view.View.OnClickListener" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/sampleButton"
android:onClick="@{listener}"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
Here it is, thank you!
@JosephSanjaya I copied and run your code, no crash happened
I didn't get crashed either when in staging build, but it listed in my Application Crashlytics Dashboard on production build, and it happened occasionally.
Hey, mind giving 1.0.0-alpha03 a go?
Sure, sir
Thank you for your reply...