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

Asked

Viewed 320 times

1

I recently asked myself a question, seemingly simple, that I could not answer and I did not find any 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’ve read they use it and I’ve learned that way. But none of them explain why to use with Bundle. It would be because of the life cycle of Activity and Fragment or because of the use of Case 2?

EDIT:

Complementing the Ramaral response. There is an example that makes it easy to understand 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 to developer options, enable "Don’t Keep activities" option. Overwrite the method onSaveInstanceState. Navigate from Activity A to B and then go back to A, and check the Bundle that comes as a parameter of onSaveInstanceState is always null.

  • 1

    Yes, it is because of the life cycle of Fragment himself. When he is recreated (and this will happen), his method (case 1) will not be called. You have it in your own documentation...

1 answer

4


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

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

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

The way that Android programmers found to solve 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 this purpose.

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

  • Thanks @ramaral. My doubt was exactly at this point of the object initialization.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.