BlackHatSamurai BlackHatSamurai - 1 year ago 118
Android Question

Why do I want to avoid non-default constructors in fragments?

I am creating an app with

and in one of them, I created a non-default constructor and got this warning:

Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead

Can someone tell me why this is not a good idea?

Can you also suggest how I would accomplish this:

public static class MenuFragment extends ListFragment {
public ListView listView1;
Categories category;

//this is my "non-default" constructor
public MenuFragment(Categories category){
this.category = category;

Without using the non-default constructor?

Answer Source

Make a bundle object and insert your data (in this example your Category object). Be careful, you can't pass this object directly into the bundle, unless it's serializable. I think it's better to build your object in the fragment, and put only an id or something else into bundle. This is the code to create and attach a bundle:

Bundle args = new Bundle();
args.putLong("key", value);

After that, in your fragment access data:

Type value = getArguments().getType("key");

That's all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download