FtheBuilder FtheBuilder - 3 months ago 18
Android Question

Android - Fragments, using reference to call instance methods

I have specific fragments which will perform actions in a background thread (or will start activities for result) and I would like to set a callback (from the hosting activity), to get some data from the fragment after such actions, for instance:

FragmentManager fm = getFragmentManager();
TakePhotoFragment takePhotoFragment = (TakePhotoFragment) fm.findFragmentById(R.id.frTakePhoto);
takePhotoFragment.setListener(new TakePhotoFragment.OnNewBitmapListener() {
@Override
public void onNewBitmap(Bitmap bitmap) {
// do things in the activity
}
});


I have read that it is safer to feed arguments into the fragment using
Bundle
s, but there are several cases which I would like to pass object references rather than simple
String
data using Bundles. Is there any problem in getting a reference using a
FragmentManager
and calling methods on it? If yes, which are the workarounds?

Answer

If your fragment is not yet created use bundle, otherwise use instance one.

It is safer to pass bundle becoz when android recreate your fragment your pass data in bundle is not lost.

If you use the instance one to pass data you have to save and restore that data yourself

Note: you can pass complex object through bundle by making them parcelable or serializable. Also passing big data in bundle is not recommended

If your fragment is defined in xml you can get the instance by findFragmentById() of fragmentManager class