0

My fragment2 class has an array of students, I want to get the array from my activity class.

My activity class extends AppCompatActivity implements Communicator. I need it to extend AppcompatActivity because Im using a toolbar.

Activity class handles the communication between Fragment 1 and 2. Anyone has any solution on how to do this?

CookieMonster
  • 241
  • 1
  • 9
  • 26
  • So from the fragment you want to access the array that's in the Activity? or you want to access the array in the activity from the fragment? – Nick H Apr 18 '16 at 16:22
  • No I have an array in the fragment2, I want to access it from the activity – CookieMonster Apr 18 '16 at 16:25

3 Answers3

0

Define an interface in your Fragment that is implemented by your Activity.

More info Here

RScottCarson
  • 980
  • 5
  • 20
0

In order to reuse the Fragment UI components, you should build each as a completely self-contained, modular component that defines its own layout and behavior.

An Activity can act as a container of the Fragments. So, if one Fragment needs to pass something to another Fragment, it can pass it to the Activity, which in turn can pass it to the other Fragment.

The ideal way of doing it is to have a Callback interface defined in your Fragment and have the Activity implement it. In your Fragment you call one of the Callback methods passing it the array or the item. In the implementation of the method, in the Activity, it can consume it / pass it to other Fragment.

More information on Fragment - Activity communication is here.

jaibatrik
  • 6,770
  • 9
  • 33
  • 62
0

If you are attempting to access objects inside a fragment from the hosting activity, you would typically hold a reference to the fragment inside the Activity and call a 'get' method directly on the fragment.

If it is the reverse (Fragment > Activity) you would have the Activity implement some sort of interface, and inside the onAttach() method of the fragment you would cast the Activity (or Context) to the Interface.

Nick H
  • 8,897
  • 9
  • 41
  • 64
  • Fragment1 adds names from edittext > Activity passes name to F2 > fragment2 adds names to array and displays the names in a listview. I want to get the array from Fragment 2, so the best solution would be to create a instance of fragment2 in my activity class and get the array? would that get the array? – CookieMonster Apr 18 '16 at 16:36
  • I believe you should use the interface. That way when the array is ready you can simply pass it to the Activity and the Activity can handle it from there. – RScottCarson Apr 18 '16 at 16:39