Reputation: 23
https://developer.android.com/topic/libraries/view-binding
I used View Binding at fragment as an official document. After networking, This code caused NPE.
private val binding get() = _binding!! (line:62)
I initialized _binding at onCreateView and I tried networking at onStart. And following codes are after networking.
override fun getTimeSuccess(challengeTimeResponse: ChallengeTimeResponse) {
when (challengeTimeResponse.code) {
1000 -> {
binding.timerStart.visibility = View.INVISIBLE //(line:256)
...} ... }}
This is my error logs.
Fatal Exception: kotlin.KotlinNullPointerException
at com.alice.timer_at_home.src.timer.TimerFrag.getBinding(TimerFrag.kt:62)
at com.alice.timer_at_home.src.timer.TimerFrag.getTimeSuccess(TimerFrag.kt:256)
at com.alice.timer_at_home.src.timer.TimerService$getChallengeTime$1.onResponse(TimerService.kt:80)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$1.run(DefaultCallAdapterFactory.java:83)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7811)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
This error doesn't always happen, but it happens sometimes. Why is this happening? What should I do to solve this problem?
Upvotes: 1
Views: 1365
Reputation: 651
As stated in the article, binding is only valid between onCreateView and onDestroyView.
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
You mentioned that you call this code after networking. I suppose there are two possible reasons for NPE:
Network request finishes after fragment destruction. To solve this problem, you should cancel all requests in onDestroyView. Or in onStop to be symmetrical to onStart.
getTimeSuccess
is called from a background thread. I can't verify that from the question description. But if it's the case, then _binding may be null sometimes because of thread variables visibility. To solve this problem, you should switch work to the main thread.
Upvotes: 3