Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragments Retaining Data

How does one best retain data within a Fragment as its activity goes through an onCreate/Destroy cycle like from Rotation?

In our setup we have potentially large lists loaded from our servers into the fragments custom list adapter and we want to smooth out the UX by not making them reload on rotation. The problem we had with setting the fragment retainInstance=true; is that our adapter has a reference to the context of the original activity and would therefore leak memory. Could we just store the data in the fragment and re-create the adapter; amd if so is that really proper practice?

The next idea is to store the data into a session singleton object and retrieve after rotation which presents a few problems with stale data but we can easily overcome.

The other alternative I see, that seems like it is the *best solution, is to save the data into a bundle and restore into the new fragment after rotation; However, we have quite a few objects that would need to be stored throughout the app and some of our objects are complex, contain lists, multiple types, and would be a pain to make parcelable. Is there a better solution or do we have to bite the bullet and make them Parcelable?

like image 433
Zachary Moshansky Avatar asked Aug 07 '12 20:08

Zachary Moshansky


People also ask

What will happen if an activity with a retained fragment is rotated?

Fragments — Scenario 3: Activity with retained Fragment is rotated. The fragment is not destroyed nor created after the rotation because the same fragment instance is used after the activity is recreated.

How can we pass data from fragment to fragment?

Passing Data between fragments in Android using ViewModel: To actually pass the data between fragments, we need to create a ViewModel object with an activity scope of both the fragments, initialize the ViewModel , and set the value of the LiveData object.


1 Answers

Just prevent the Activity from recreating itself on rotation (etc). Add

android:configChanges="keyboardHidden|orientation|screenSize"

to your Activity definition in your AndroidManifest.xml. Then there's no need for saving anything on rotation.

EDIT:

If you don't like that solution then you've got no choice but to use the onSaveInstanceState mechanism. If you've got complex data, just make your classes Serializable and add them to the Bundle that way.

like image 198
Christopher Perry Avatar answered Sep 27 '22 19:09

Christopher Perry