Answer the question
In order to leave comments, you need to log in
How to make one data model for multiple android fragments?
There is a model in the form of a large non-trivial object with a bunch of fields. Within an Activity, multiple fragments must work with this object. Very similar to the Observer pattern. Everywhere advice is given to use the fragment.setArguments(bundle) function to pass data to fragments via the API. But I don't understand why copy data and waste memory. What is wrong with the approach when we simply create a model in the Activity and pass in the constructor to each fragment a reference to this model?
Answer the question
In order to leave comments, you need to log in
The fact that the system can kill the fragment and recreate it. Of course, the system will pass nothing to the constructor.
The model for good should not be stored in RAM, but should, for example, be stored in the database. How to update and load data from the database is up to you.
and if you look at the implementation of the fragment manager?
you will see that when restoring the state, it will pull an empty constructor, which is why it makes no sense to add your own constructor with parameters to the fragments.
either there will be an error, or nothing.
I don't have models at all. just observers on the database, something has changed in the database, it changes in other fragments.
If you have one activity or data needs to be transferred only inside this activity, then you can use this trick:
1) create a model
2) create an empty fragment in the constructor, create a model, and in onCreate call the setRetainInstance(true) method; (this is to protect the fragment from destruction and recreate)
public class SignInWorkerFragment extends Fragment {
private final SignInModel mSignInModel;
public SignInWorkerFragment() {
mSignInModel = new SignInModel();
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public SignInModel getSignInModel() {
return mSignInModel;
}
}
final SignInWorkerFragment retainedWorkerFragment =
(SignInWorkerFragment) getFragmentManager().findFragmentByTag(TAG_WORKER);
if (retainedWorkerFragment != null) {
mSignInModel = retainedWorkerFragment.getSignInModel();
} else {
final SignInWorkerFragment workerFragment = new SignInWorkerFragment();
getFragmentManager().beginTransaction()
.add(workerFragment, TAG_WORKER)
.commit();
mSignInModel = workerFragment.getSignInModel();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question