Fragment callback methods called twice after rotating the device

Viewed 31

I have following logic in my Activity :

protected abstract val fragment: BaseSearchFragment<T>

override fun onCreate(savedInstanceState: Bundle?) {
   ...
   replaceFragmentInActivity(fragment, R.id.fragment_container)
}

Now when I rotate the device fragment Callbacks get called twice such as onCreate in the fragment, since I replaced the fragment in Activity. I want to use onSaveInstanceState in the fragment, but since it is called twice the logic will not work as expected since for the 2nd fragment creation, savedInstanceState will be null.

If I use following in the Activity :

if(savedInstanceState == null) {
   addFragmentToActivity(fragment, R.id.fragment_container)
}

I will face with another problem since I have following in the activity :

searchView.setOnQueryTextListener(object : OnQueryTextListener {

    override fun onQueryTextChange(query: String): Boolean {
       fragment.search(query)
       return true
    }
}

And here is fragment search method :

fun search(query: String) {
        if (searchViewModel.showQuery(query)) {
            binding.recyclerView.scrollToPosition(0)
            tmdbAdapter.submitList(null)
        }
    }

Here when I am rotating the device I receive following exception :

java.lang.IllegalStateException: Can't access ViewModels from detached fragment

So, is there any solution that when I rotate the device fragment Callbacks get called just once?

You can check the source code here : https://github.com/alirezaeiii/TMDb-Paging

0 Answers
Related