I recently asked myself a seemingly simple question that I could not answer and found no concise answer. The question is simple: Why use Bundle instead of a set method to pass parameters from an Activity to a Fragment?
For example:
Case 1:
public static MyFragment getInstance(String myAttr){
MyFragment myFragment = new MyFragment();
myFragment.setMyAttr(myAttr);
return myFragment;
}
Case 2:
public static MyFragment getInstance(String myAttr){
MyFragment myFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("myAttr", myAttr);
myFragment.setArguments(bundle);
return myFragment;
}
I always use Case 2 because in all the books I have read, I have learned it. But none of them explains why to use Bundle. Would it be because of the activity and fragment life cycle because of the use of Case 2?
EDIT:
Complementing the Ramaral response.
There is an example that makes it easy to see why it is necessary to use Case 2 instead of Case 1.
Just do two activities, A and B for example. And give commit()
in a fragment, instantiated as in case 1, in activity A.
Go in the developer options, enable the "Do not keep activities" option.
Overwrite the onSaveInstanceState
method.
Navigate from activity A to B and then back to A, and checking the bundle that comes as a parameter of onSaveInstanceState
is always null.