1

When passing data to a fragment why do this - (i.e. the way you are supposed to do it)

private String mParam1;
private String mParam2;



public static ReviewPagesFragment newInstance(String param1, String param2) {
    ReviewPagesFragment fragment = new ReviewPagesFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

instead of doing this

private String mParam1;
private String mParam2;



public static ReviewPagesFragment newInstance(String param1, String param2) {
    ReviewPagesFragment fragment = new ReviewPagesFragment();
    fragment.mParam1 = param1;
    fragment.mParam2 = param2;
    return fragment;
}

the second way is simpler and gives you better performance. I am a fan of K.I.S.S. So my question is - why is the first way the recommended way and what benefit come from doing it that way?

Tyler Davis
  • 2,420
  • 2
  • 23
  • 19
  • 1
    Some time ago I asked very similar question ;) - If you would like to see it was explained there see: http://stackoverflow.com/questions/10316527/dailogfragment-getarguments-setarguments-why-passing-arguments-in-a-bundle – Tomasz Gawel Aug 18 '14 at 15:25

1 Answers1

4

Using a Bundle allows your fragment to persist state if it's recreated. Here's a more thorough explaination: Best practice for instantiating a new Android Fragment

Community
  • 1
  • 1
Submersed
  • 8,810
  • 2
  • 30
  • 38