Claud Kho
Claud Kho

Reputation: 426

How to change non-default constructor in fragments to default constructor?

Code:

public PlacePickerFragment() {
    this(null);
}
public PlacePickerFragment(Bundle args) {
    super(GraphPlace.class, R.layout.com_facebook_placepickerfragment, args);
    setPlacePickerSettingsFromBundle(args);
}

Hello, I want to remove deprecation warning from code above, is there a way changed it to default constructor?

Upvotes: 2

Views: 6353

Answers (3)

Andy
Andy

Reputation: 2507

The answer by Lawrence Choy was very helpful, but did not work for me as the super() call do not accept the args variable. This worked for me:

public void initialize() {
  Bundle args = getArguments();
  setPlacePickerSettingsFromBundle(args);
}

/**
  * Default constructor. Creates a Fragment with all default properties.
  */
public PlacePickerFragment() {
  super(GraphPlace.class, R.layout.com_facebook_placepickerfragment, null);
}

Upvotes: 0

Lawrence Choy
Lawrence Choy

Reputation: 6108

When you create your fragment, use setArgument():

Bundle args = new Bundle();
// Construct your bundle here
Fragment mFragment = new PlacePickerFragment();
mFragment.setArguments(args);
mFragment.initialize();

And use fragment's default constructor. You may need to call setPlacePickerSettingsFromBundle() after you have set the arguments, something like this:

public PlacePickerFragment() {
    super(GraphPlace.class, R.layout.com_facebook_placepickerfragment, args);
}

public void initialize() {
    Bundle args = getArguments();
    setPlacePickerSettingsFromBundle(args);
}

Upvotes: 6

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52956

Get rid of the Bundle parameter and make the constructor take no arguments. Then use setArguments() to pass the bundle. If necessary, create static factory method to create your fragment with the necessary arguments.

Upvotes: 1

Related Questions