I have a gallery app. In which I have used RecycylerView
to show photos. I want to save the content of UI whenever user leaves the app in onStop()
and restore the same content whenever the user opens app again in onCreate()
. In short I want to eliminate image loading , show the previous UI and then after I can load images in background. So, User won't see image placeholders. And will feel that images are loaded instantly.
Example
Suppose you are using Instagram. You pressed home button and navigated to WhatsApp. Sent some messages and came back to Instagram. You found that your screen looks the same. Because when onPause()
event was triggered OS saved the UI state. (I don't exactly know what android OS will save when onPause()
is triggered.) And restored the same when onResume()
Event is triggered.
The same is happening with my app even I am not saving anything at all in onPause()
. So, I want to save that data or UI state in onStop()
which is being saved in onPause()
by OS. And want to restore the same in onCreate()
.
What I have Tried
I tried to save the state of RecyclerView
in onStop()
and restoring it whenever the adapter
is attached.
...
@Override
public void onStop() {
super.onStop();
State = layoutManager.onSaveInstanceState();
}
...
adapter = new PhotosAdapter(requireActivity().getApplicationContext(), arrayList, getActivity(), this);
recyclerView.setAdapter(adapter);
layoutManager.onRestoreInstanceState(State);
...
But, this didn't work. I had issue that if user is in the middle of RecyclerView
and presses home button and then gets back to app RecyclerView
will be shown from top and user has to scroll again to middle. So, I found that saving state in onPause()
solves the issue. So, I thought it might be saving the whole layoutManager
. And tried it to save it in onStop()
. But, as expected it didn't work.
I know that overriding onSaveInstanceState()
can help. But, Here it's not about int,string or any data type. I want to save whatever is on the screen in onStop()
and whatever data is saved by OS in onPause()
. And finally want to restore that data in onCreate()
.
Please Guide me to further steps.
You should try to save the values in savedInstanceState and try to restore it.
As official documentation suggests to use ViewModel
as well to store the complex data.
To bridge the gap between user expectation and system behavior, use a combination of ViewModel objects, the onSaveInstanceState() method, and/or local storage to persist the UI state across such application and activity instance transitions. Deciding how to combine these options depends on the complexity of your UI data, use cases for your app, and consideration of speed of retrieval versus memory usage.