1

What will be the implications if I passed an object to a fragment without using bundle? I just opened one of the old code and found it there and couldn't help asking this question as I have never tried it. Also I am not finding any memory leaks in it.

This is how it is implemented -

Activity class:

MyFragment fragment =
        MyFragment.newInstance(getIntent().getStringExtra(DATA),
            instance.getCallback(),
            instance.getRequest());
    getSupportFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();

Fragment class:

public class MyFragment extends Fragment {

  public MyFragment() {
    /* Required empty public constructor */
  }

  public static MyFragment newInstance(String data, Callback callback,
      Request request) {
    MyFragment fragment = new MyFragment();
    fragment.setCallback(callback);
    fragment.setRequest(request);
    fragment.setData(data);
    return fragment;
  }

  private void setCallback(Callback callback) {
    this.callback = callback;
  }

  private void setData(Data data) {
    this.data = data;
  }

  private void setRequest(Request request) {
    this.request = request;
  }
}

Generally, what I have used till date is Fragment#setArguments(Bundle)

Aurelius Prochazka
  • 4,510
  • 2
  • 11
  • 34
Jimit Patel
  • 4,265
  • 2
  • 34
  • 58
  • 1
    If you use data external to your fragment, that is from a getter setter from a singleton class, then obviously the data will not be the property of the fragment. You also will have to struggle to wipe that data out from the memory. – Abhinav Saxena Dec 07 '18 at 12:28
  • Thanks. So you mean chances for memory leaks are there in this case. I failed to get any of those though. But even I suspected memory leaks will be there – Jimit Patel Dec 07 '18 at 12:30
  • Yes, that is why it is forbidden to have static pointers to any context based variables, like view, activity, so on... – Abhinav Saxena Dec 07 '18 at 12:32

1 Answers1

3

Please check out this answer: Why its not recommended to pass object to fragment with simple getter setter.

Long story short, you will lose your data on configuration changes.

There are mainly two ways of communicating with a fragment: via bundles or via an interface that you implement in your activity. Please see this link in order to see how to properly communicate with a fragment via an interface: https://developer.android.com/training/basics/fragments/communicating