FtheBuilder FtheBuilder - 1 year ago 102
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() {
public void onNewBitmap(Bitmap bitmap) {
// do things in the activity

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

Answer Source

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

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