0

I have a project activity (MainActivity) using tabs, each tab launches a fragment (MyFragment). The fragments are not implemented in the project, but are implemented in a referenced library project.

So I want to pass a simple object from the Activity to the Fragment:

private MySimpleClass myObject = new MySimpleClass();

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    static final String KEY = "simpleObject";
    final ActionBar actionBar = getActionBar();
    Bundle args = new Bundle();
    switch( tab.getPosition() ) {
    case 0:
        fragment = new MyFragment();
        args.put??????(KEY, myObject);
        fragment.setArguments(args);
        fragmentTransaction.add(R.id.fragmentContent, fragment, "tab0_tag");
        break;
        . . .

    }
}

If the Fragment would not have been in a library I would have bypassed the Bundle mechanism and just use a local method:

 m = ((MainActivity)getActivity()).getMyObject();

But this does not work from the library Fragment code, since it does not recognize MainActivity and thus cannot cast to it.

ilomambo
  • 8,290
  • 12
  • 57
  • 106

1 Answers1

0

If I'm not misunderstanding, you're still in control of the library code, even though it's a separate project. If so, this sounds like the textbook use case for constructor injection: In the library, create a constructor for the fragment that accepts the object in question as a parameter, enabling you to call

fragment = new MyFragment(myObject); // <-- HERE
fragmentTransaction.add(R.id.fragmentContent, fragment, "tab0_tag");

If you are not in control of the library code, then the library must have some functionality to be provided with the object.

balpha
  • 50,022
  • 18
  • 110
  • 131
  • I am in control of the library project as well. I tried your suggestion but it does not compile, with the following error (although it reads as a warning it is an error) `Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead` – ilomambo May 09 '13 at 18:58
  • Although after project->clean, the error/warning disappeared! Great Advise! – ilomambo May 09 '13 at 19:01
  • Hmm yeah, this may not have been a great idea after all: http://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment – balpha May 10 '13 at 09:20
  • I don't think so. The solution you suggested works for me. And besides, not able to use a `Bundle` to pass my arguments was my problem in the first place, so moving `setArguments()` inside `newInstance()` does not solve anything for me. – ilomambo May 10 '13 at 12:06