CuirMoustachu CuirMoustachu - 5 months ago 37
Java Question

Why its not recommended to pass object to fragment with simple getter setter

I'm new to android, I wonder why this easy method for parameter passing is not recommended.

class DemoFragment extends Fragment{
private MyObject myObject;
public void setMyObject(MyObject myObject){
this.myObject = myObject;

DemoFragment fragmentDemo = new DemoFragment();


The mechanism that Android provides for parameter passing to Fragments is using Bundles, which is the same technique in Activity to Activity data passing.

When creating your Fragment, call its setArguments(Bundle bundle) method with the desired key-values that you want.

Also another advantage is that you can persist this arguments during configuration changes in the device, like the orientation change.

Using getters and setters is not a bad practice generally, but you better take the most out of the native APIs before trying to reinvent the wheel.