Reputation: 131
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();
fragmentDemo.setMyObject(myObject);
Upvotes: 1
Views: 1242
Reputation: 14755
Why using Bundles instead of simple setters?
When you rotate the screen of the device (a.k.a. "orientation change" or " configuration change") the fragment DemoFragment
is destroyed and then recreated by android. So the content of DemoFragment.myObject
is lost after the rotation if supplied via the setter.
The non-intuitive "Bundle" info is not lost after screen rotation. When DemoFragment is re-created it receives the data from the bundle again so DemoFragment.myObject
is filled again with the required parameter.
For more details see https://developer.android.com/training/basics/activity-lifecycle/index.html
If it doesn-t matter that a class member get lost after "screen rotation" then setters are fine.
Upvotes: 4
Reputation: 12986
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.
Upvotes: 2