Skip to content Skip to sidebar Skip to footer

Android - View Instance Gets Null On Screen Rotation

I am using Kotlin Android Extension to access view directly by their id. I have a progress bar which I access directly in fragment using id i.e progress_bar

Solution 1:

In my case this bug happens from time to time. Of course, onViewCreated() is a good method to place your code in. But sometimes it's strangely not enough. And setRetainInstance(true) may help, may not. So sometimes this helps: access your Views with a view variable. You can even access them inside onCreateView(). You can use ?. for a guarantee that an application won't crash (of course, some views won't update in this case). If you wish to get context, use view.context.

In my case this bug reproduced only in Kotlin coroutines.

privatefunshowProgress(view: View) {
    view.progressBar?.visibility = View.VISIBLE
}

privatefunhideProgress(view: View) {
    view.progressBar?.visibility = View.GONE
}

Then in code:

overridefunonViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    showData(view)
}

privatefunshowData(view: View) {
    showProgress(view)
    adapter = SomeAdapter()
    adapter.setItems(items)
    val divider = SomeItemDecoration(view.context)
    view.recycler_view?.run {
        addItemDecoration(divider)
        adapter = this@SomeFragment.adapter
        layoutManager = LinearLayoutManager(view.context)
        setHasFixedSize(true)
    }
    hideProgress(view)
}

Solution 2:

In which method do you get the progress_bar by Id?

Please consider the fragment state lifecycle. Maybe you try to load it when the view is not ready yet.

Ensure your progress_bar variable is assigned only after the view is ready. For example in the onViewCreated method.

See here the official Android lifecycle:

Official Android lifecycle

Update

As @CoolMind pointed out the diagram doesn't show the method onViewCreated.

The complete Android Activity/Fragment lifecycle can be found here:

The complete Android Activity/Fragment lifecycle

Solution 3:

Add retain intance true to the fragment so that it will not be destroyed when an orientation changes occurs

overridefunonCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    retainInstance=true
}

Also do a null check using safe call operator before accessing views

funshowHideProgressBar(visible: Boolean) {
    progress_bar_web_control?.visibility = if (visible) View.VISIBLE else View.GONE
}

Post a Comment for "Android - View Instance Gets Null On Screen Rotation"