Factory method for Fragment: Setting the class variables vs putting the Bundle as arguments in the Fragment

192 views Asked by At

I have been reading about the use of a factory method to get hold of an object of a custom Fragment class. Let say I have a custom Fragment class as follows:

public class CustomFragment extends Fragment {

    ..........

    public static CustomFragment getInstance(String message) {
        CustomFragment fragment = new CustomFragment();
        Bundle bundle = new Bundle();
        bundle.putString(MESSAGE, message);
        fragment.setArguments(bundle);
        return fragment;
    }
   ..............
}

What if I have a class variable named MESSAGE and I set its value using the setter on the instantiated object like:

public class CustomFragment extends Fragment {

    ..........
    private String MESSAGE;

    private void setMessage(String msg) {
        this.MESSAGE = msg;
    }

    public static CustomFragment getInstance(String message) {
        CustomFragment fragment = new CustomFragment();
        fragment.setMessage(message);
        return fragment;
    }
   ..............
}

Which of the above two is preferred and why?

1

There are 1 answers

2
CommonsWare On BEST ANSWER

Which of the above two is preferred

The first one.

why?

Users will rotate the screen or otherwise trigger your app to undergo a configuration change. Your foreground activity, and its fragments, are destroyed and recreated by default. In your first scenario, the message will be part of the saved instance state Bundle and will not be lost. In your second scenario, the message will be lost, unless you add extra code somewhere to specifically hold onto it.