Hello friends, I’m experiencing NullPointerExcepti...
# android
l
Hello friends, I’m experiencing NullPointerExceptions on my fragments when I migrated it to ViewBinding. I am following exactly based on the documentation https://developer.android.com/topic/libraries/view-binding#kts but it will throw NullPointerException on the
private val binding get() = _binding!!
line. Thanks in advance for the help!
w
Can you make sure you are not calling it before the
onCreateView
and after the
onDestroyView
?
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
Quick and dirty one to check:
Copy code
private var _binding: ResultProfileBinding? = null
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding: ResultProfileBinding get() {
        println("test binding get")
        return _binding!!
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        println("test onCreateView")
        _binding = ResultProfileBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }

    override fun onDestroyView() {
        println("test onDestroyView")
        super.onDestroyView()
        _binding = null
    }
Look in the Logcat to see if the
test binding get
calls either before the
test onCreateView
or after the
test onDestroyView
.
l
Thanks for the code snippet @wbertan and yes I am not calling it before
onCreateView
and after
onDestroyView
. I did follow everything on the Android documentation link. I will try your implementation.
w
Asking as we are having some crashes related to this too. We had a leak somewhere where it was calling it after the
onDestroyView
in some cases only due to the leak 😞
l
The issue is when I try to click rapidly on each Fragment. The Fragment is hosted on the
BottomNavigationView
. It seems ViewBinding can’t catch up on the rendering.
Can you @ me on your progress @wbertan? If you made some improvements or fixes
w
We are also using the same implementation as the docs 😞 Could be something like our case, some listener, etc. which outlives the Fragment View and it calls after the
onDestroyView
. In some places after migrating to View Binding we also had to explicitly remove listeners on the
onDestroyView
.
j
you have to reinitialize always when you create a view, so in fragments any time onCreateView is called the view binding has to be initialized. Fragments views can be recreated
you can use a delegation method to do this automagically
l
Thanks let me check that out. Do you have an example as my guide?