0

I want to know that is it a good practice to set the objects directly when creating a new Fragment like in the example below or should we always make our object Parcelable and pass through intent?

public class sample extends Fragment {

private Object obj1;

public static sample newInstance(Object obj) {
     sample fragment = new sample();
    fragment.setObj1(obj);
    return fragment;
}

public void setObj1(Object obj1) {
    this.obj1 = obj1;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    return super.onCreateView(inflater, container, savedInstanceState);
}

}

In either case, it will be helpful if someone could give me reasons why one is better than the other?

OkDroid
  • 185
  • 3
  • 11
  • 1
    Possible duplicate, https://stackoverflow.com/questions/37765613/why-use-bundle-to-pass-data-to-fragment – zvone Oct 02 '17 at 21:03

1 Answers1

1

Yes you must use setArguments with a Bundle with all your Parcelables.

Thats because when recreated your Fragment will only have access to it getArguments() and all local variables will be null (or default for primitives).

The way to go is in your newInstance

public static sample newInstance(String obj) {
   sample fragment = new sample();
   Bundle args = new Bundle();
   args.putString(STRING_PARAM_KEY, obj);
   fragment.setArguments(args);
   return fragment;
}

Then in your onCreateView

 obj1 = getArguments().getString(STRING_PARAM_KEY);

Just declare in your class a constant for the key

 static final String STRING_PARAM_KEY = "string_param_key";
Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167