As per the android documentation, To get the data binding within a fragment, I use a non-nullable getter, but sometimes' When I try to access it again, after I'm wait for the user to do something, I receive a NullPointerException.
private var _binding: ResultProfileBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,
savedInstanceState: Bundle?): View? {
_binding = ResultProfileBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViews()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun setupViews() {
// On click listener initialized right after view created, all is well so far.
binding.btnCheckResult.setOnClickListener {
// There is the crash when trying to get the nonnull binding.
binding.isLoading = true
}
}
Does anyone know what the cause of the NullPointerException crash is? I'm trying to avoid not working according to the android documentation, and do not return to use nullable binding property (e.g _binding?.isLoading). Is there another way?
I can't explain why you're having any issue in the code above since a View's click listener can only be called while it is on screen, which must logically be before onDestroyView() gets called. However, you also asked if there's any other way. Personally, I find that I never need to put the binding in a property in the first place, which would completely avoid the whole issue.
You can instead inflate the view normally, or using the constructor shortcut that I'm using in the example below that lets you skip overriding the onCreateView function. Then you can attach your binding to the existing view using bind() instead of inflate(), and then use it exclusively inside the onViewCreated() function. Granted, I have never used data binding, so I am just assuming there is a bind function like view binding has.
class MyFragment: Fragment(R.layout.result_profile) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = ResultProfileBinding.bind(view)
// Set up your UI here. Just avoid passing binding to callbacks that might
// hold the reference until after the Fragment view is destroyed, such
// as a network request callback, since that would leak the views.
// But it would be fine if passing it to a coroutine launched using
// viewLifecycleOwner.lifecycleScope.launch if it cooperates with
// cancellation.
}
}
Related
Do I have to free my custom ArrayAdapters in fragments, like I do it with binding? And also what about ArrayList that holds the data?
Inside my Fragment class I have:
private var binding: FragmentUhfReadBinding? = null // init onCreateView, free onDestroyView, use onViewCreated
private var listAdapter: ReadUhfTagInfoItemViewAdapter? = null // init in onViewCreated
private val arrayList: ArrayList<ReadUhfTagInfo?>? = ArrayList()
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentUhfReadBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
// do I have to set `listAdapter` to null here?
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
listAdapter = ReadUhfTagInfoItemViewAdapter(this.context, arrayList)
binding!!.lvData.adapter = listAdapter
}
Yes, because your adapter is referencing a context (which is the attached Activity).
It's also referencing a list that you have created only in your Fragment, but it's debatable whether you should care if that's leaked. It would be more typical for backing list data to be in a ViewModel so it could be reused, in which case this list reference your adapter is holding wouldn't be a problem.
Although your example doesn't show it, it's also very common for an adapter to expose some kind of listener for view interactions. So when you add this, and your listeners capture references to other stuff in the fragment, then the adapter would also be leaking the memory of those things.
However, it is not common in the first place to need your binding and your adapter to be in class properties. If you use them solely within onViewCreated() and functions called by onViewCreated(), then you don't need to worry about clearing references to them, and you won't have the ugly use of !!, so it will be more robust.
Instead of inflating a view with onCreateView(), you can pass a layout id to the superconstructor, and then create your binding by calling bind with the pre-existing view in onCreateView().
class MyFragment: Fragment(R.layout.fragment_uhf_read) {
private val arrayList: ArrayList<ReadUhfTagInfo?> = ArrayList()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentUhfReadBinding.bind(view)
val listAdapter = ReadUhfTagInfoItemViewAdapter(this.context, arrayList)
binding.lvData.adapter = listAdapter
// ... other code using binding and listAdapter
}
}
I'm playing around with Kotlin on Android and one thing makes me confused.
When I converted few Fragments from Java to Kotlin I got this:
class XFragment : Fragment() {
private var binding: FragmentXBinding? = null
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentUhfReadBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding!!.slPower.addOnChangeListener(this)
binding!!.btnClearTagList.setOnClickListener(this)
}
// ...
private fun updateUi(){
binding!!.someTextView.text = getSomeTextViewText()
binding!!.someSlider.value = getSomeSliderValue()
}
}
I can't make binding non-nullable, because it has to be initialized after XFragment class constructor, in onCreateView() or later.
So with this approach it has to be nullable and I have to put !! everywhere.
Is there some way to avoid these !!?
The official documentation suggests this strategy:
private var _binding: FragmentXBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
Ultimately, it becomes just like requireActivity() and requireContext(). You just need to remember not to use it in a callback that might get called outside the view lifecycle.
Note, you can create your view using the super-constructor layout parameter and then bind to the pre-existing view in onViewCreated. Then you might not even need to have it in a property. I rarely need to do anything with it outside onViewCreated() and functions directly called by it:
class XFragment : Fragment(R.layout.fragment_x) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentXBinding.bind(view)
binding.slPower.addOnChangeListener(this)
binding.btnClearTagList.setOnClickListener(this)
}
}
The application started to receive some crashes (it is not reproducible 100%) due to some lifecycle issue for the Fragment.
I'm using view binding and I'm manually invalidating the binding as per Android recommendations to avoid high memory usage in case the reference to the binding is kept after the Fragment is destroyed.
private var _binding: FragmentCustomBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View = FragmentCustomBinding.inflate(inflater, container, false).also {
_binding = it
}.root
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
override fun onSaveInstanceState(outState: Bundle) {
outState.apply {
putString(BUNDLE_KEY_SOME_VALUE, binding.etSomeValue.text.toString())
}
super.onSaveInstanceState(outState)
}
I'm getting a NullPointerException in onSaveInstanceState() as the binding is null as this was called after onDestroyView().
Any idea how I could solve this without manually creating a saved state and manually handling it?
The binding = null is causing the issue. To get rid of the _binding = null in the correct manner use this code:
class CustomFragment : Fragment(R.layout.fragment_custom) {
private val binding: FragmentCustomBinding by viewBinding()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Any code we used to do in onCreateView can go here instead
}
}
According to an article on this workaround:
This technique uses an optional backing field and a non-optional val which is only valid between onCreateView and onDestroyView.
In onCreateView, the optional backing field is set and in onDestroyView, it is cleared. This fixes the memory leak!
It seems the answer for this is in how the fragments are handled, even when they do not have a view, as changes in the Activity state can still trigger onSavedInstanceState() thus I can end up in scenarios where I am in onSavedInstanceState() but without a view.
This seems to be intentional as fragments are still supported whether they have a view or not.
The recommendation was to use the view APIs for saving and restoring state (or my SavedStateRegistery).
A few more details can be found here: https://issuetracker.google.com/issues/245355409
I have a ParentFragment and a ChildFragment. They are working pretty fine.
My problem is that in the future I might create many child fragments and this makes me write this boilerplate code for every single child fragment. Thus, I would like to optimize my ParentFragment so that I do not have to write boilerplate code for every single new child framment I create in the future.
ParentFragment
abstract class ParentFragment<T: ViewDataBinding>: Fragment() {
#LayoutRes
abstract fun getLayoutResId(): Int
protected lateinit var binding: T
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return DataBindingUtil.inflate<T>(inflater, getLayoutResId(), container, false).apply { binding = this }.root
}
ChildFragment
class ChildFragment: ParentFragment<FragmentChildBinding>() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//THIS IS THE BOILERPLATE METHOD I AM TALKING ABOUT.
//I WOULD LIKE TO MOVE THIS CODE IN THE PARENTFRAGMENT
initBinding()
}
#LayoutRes
override fun getLayoutResId() = R.layout.fragment_child
fun initBinding() {
val viewModel: ChildViewModel = getViewModel() //This method is from Koin
binding.viewModel = viewModel
binding.lifecycleOwner = this
}
I tried to move this initBinding method code into ParentFragment but I got errors. Any suggestions would be greatly appreciated.
So, your current issue is that you want to make your initBinding() function common in such a way that all child fragment can access it.
Now issue is that logic inside initBinding comes with koin dependency that gets resolved dynamically. So, each child fragment may have different ViewModel instance.
There is one way you can resolve this problem:
Take your ViewModel object as method parameter so that you can inject it from your child fragment while having method in parent fragment. check out below how:
initBinding() Method in ParentFragment with viewModel as method parameter that we will pass on from child fragments.
abstract class ParentFragment<T: ViewDataBinding>: Fragment() {
// Other stuffs removed for sack of simplicity
protected fun initBinding(viewModel: ViewModel) {
binding.viewModel = viewModel
binding.lifecycleOwner = this
}
}
Accessing it from ChildFragment:
class ChildFragment: ParentFragment<FragmentChildBinding>() {
// Other stuffs removed for sack of simplicity
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// THIS IS HOW YOU CAN CONSUME THIS METHOD
initBinding(getViewModel())
}
}
You need to call serVariable() on your binding object to set ViewModel in the parent Fragment. Optionally in your parent Fragment you can get ViewModel through abstract function if child Fragments have their own ViewModels.
You can follow this post to solve your problem.
Yes, I have written my view access inside onViewCreated. So sometimes it's showing
IllegalStateException: view must not be null
Immediately if I run after cleaning the project, it's working without any error !!!
CONFUSED !
Another confusing issue is if I use view inside onViewCreated
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {myTextView.text = "MyName"}
its working fine
but if assign it inside onResponse of a Retrofit call
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
netWorkCallByRetrofit()
}
netWorkCall(){
myTextView.text = "MyName"
}
it's not working.
Immediately if I run after cleaning the project, it's working without any error !!!
Again it's working well if initialize it in onViewCreated
like
tv: TextView
tv = myTextView
tv.text = "MyName"
it's working!!!
Any clue ?
In a fragment, always make a reference to the view you are returning in onCreateView.
I tend to make a private var thisView: View? = null in the fragment main body, then in onCreateView assign that to the view you are returning. the rest of the fragment always refer to, for example thisView.myTextView.text and you shouldn't have any more weird nullpointer errors.
Some code might make this a bit less chaotic:
class MyClass: Fragment(){
private lateinit var thisView: View // can also make it nullable and set it to null here
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
thisView = inflater.inflate(R.layout.my_cool_layout, container, false)
thisView.myTextView.setOnClickListener{
toast("yaaaay")
}
return thisView
}
}