I'm dealing here with strange fragment lifecycle behavior.
I have an activity that host two fragments: CityFragment - to display cities list and WeatherFragment - to display the weather forecast for selected city.
When the app starts CityFragment is displayed on the screen, when user selects the city - WeatherFragment is added through supportFragmentManager with backstack.
Then, if user want to rotate the screen I'm getting the situation on the picture
- 0-2 -- CitiesFragment is launched
- 3-7 -- User select the city and WeatherFragment is displayed on the screen
- 8-18 -- screen rotation
As you can see in logs right after user selects the city onStop and onDestroyView are called for CitiesFragment, fragment view after this is null. But when screen rotates, CitiesFragment onSaveInstanceState is called (when the view is already destroyed).
The issue here is that after converting the code to kotlin and using synthetic for view access, I'm getting NullPointerException in onSaveInstanceState when I want to save recyclerview first visible element to restore after
val firstVisiblePosition = (recycler_view_cities.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
with old java implementation, it works fine because I store the reference for recycler_view_cities in the Fragment and I can access it there.
- Question 1. shouldn't onSaveInstance state for CitiesFragment be called before onStop and onDestroyView?
- Question 2. how to handle this kind of situation?