Why pass arguments to a Fragment using Bundle instead of a set method

0

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.

    
asked by anonymous 13.03.2018 / 19:59

1 answer

3
Whatever the situation, it is not advisable that the initial state of an object be determined by using setters .

"Good practices" recommend that the initial state of an object be determined in its construction. The object must be constructed using a constructor that receives the necessary values to create it in a valid initial state.

A Fragment is a special case as it can be destroyed and recreated by OS. Since the only way the OS has to recreate it is to use the default constructor, Fragment may not be created in a valid initial state.

The way that Android developers found to resolve this situation was to provide the method setArguments () . The Bundle passed to it should be used to place the Fragment in a valid initial state. It replaces an eventual constructor that would be used for that purpose.

When using the setArguments() method, the OS ensures that the last Bundle is always available when calling the getArguments () , even though the Fragment has been destroyed and recreated.

    
13.03.2018 / 23:07