2

I am using kotlin view binding in my fragment. In some cases app crashes with IllegalStateException & view as null, I am accessing it in a runnable which is called using a handler with a 1.5sec delay.

 numberRunnable = Runnable {
        if (mobileView.text.toString().isNotEmpty() && Utility.isMobileNumberValid(mobileView.text.toString())) {
            presenter.getCustomerDetails(Utility.getServerAcceptableContactNumber(mobileView.text.toString()))
        }
    }

mobileView is null

Handler code: handler.postDelayed(numberRunnable, 1500)

I am aware of one possibility to check if isAdded in my fragment, but since I cannot replicate the bug I am not sure if its the problem.

3
  • If your fragment is in state where it has not called onCreateView yet - or it has already called onDestroyView then Views will always be null. Commented Jan 22, 2019 at 13:41
  • It's called from onViewCreated() Commented Jan 22, 2019 at 13:44
  • 1
    Are you using "mobileView" id in different fragment layouts? If so, you should check the kotlin binding class ("kotlinx.android.synthetic....") in imports list corresponds to the fragment layout. Commented Jan 22, 2019 at 13:53

2 Answers 2

3

The action is likely running after the user leaves the Fragment and onDestroy() is called. In that state, there will be no View instances in the Fragment.

A simple workaround would be to create a global var to check your Fragment's created state. Set it to true in onViewCreated() and false in onDestroyView() (before the super call). Then check that value inside the Runnable before executing your logic.

A better solution (although this is subject to race conditions and needs every Runnable being assigned to a global variable) might be to use the Handler.removeCallbacks() method and pass all your Runnables.

override fun onDestroyView() {
    handler.removeCallbacks(numberRunnable)
}

Yet another possibility is to simply say the View is nullable:

mobileView?.let {
    //Your stuff goes in here
    //You can reference mobileView using "it"
}
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot assume that after 1.5s the views are still attached to the view hierarchy.

Add handler.removeCallbacks(numberRunnable) to your onStop() life-cycle callback to remove the numberRunnable when the fragment is not active anymore.

Also ask yourself the question of why you need to have the delay.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.