0

The official android documentation suggests that passing data from a fragment to an activity should be done by defining an interface in the fragment, and then implementing it in the activity.

However, say you have a fragment that is used by more than one activity, and that you need to pass the data only to a certain activity. Since this is Java, this solution requires I implement the interface for all of the activities, which is not a viable solution IMHO.

What methods are available and recommended to pass data from a fragment only to a certain activity?

ehehhh
  • 1,066
  • 3
  • 16
  • 27
nbubis
  • 2,304
  • 5
  • 31
  • 46
  • 1
    Cast `getActivity()` to the class of the "certain activity", then call a method on it. – CommonsWare Dec 13 '15 at 17:06
  • @CommonsWare - Good point. Do you know why the documentation suggests using an interface over `getActivity()`? – nbubis Dec 13 '15 at 19:11
  • If there are N possible hosting activities, usually the relationship between the fragment and those activities is the same. Hence, the recommendation for the interface-based communication. Your situation happens not to match that. The documentation is not going to attempt to document any and all patterns. Heck, considering that I've possibly outwritten Google, I'm happy when they cover *any* patterns. – CommonsWare Dec 13 '15 at 22:50

2 Answers2

1

For exactly same purpose i'm using Otto library. Its great for building code that is very separated from other parts of application. Otto is very simple library, more advanced developers are moving in to RX Java territory

Adam Fręśko
  • 1,064
  • 9
  • 14
1

I've occasionally solved this by sending a broadcast message from the fragment, with a bundle or other data structure, to a broadcast receiver in the activity. It may not be entirely canonical, but it works and doesn't require you to implement anything in activities that do not need to act on the message from the fragment.

alzee
  • 1,393
  • 1
  • 10
  • 21
  • Do you happen to have some example code or a reference to such code? – nbubis Dec 14 '15 at 11:07
  • It's just a standard broadcast. Create an intent and send it with sendBroadcast in the fragment, and handle it as you would any other in the BroadcastReceiver on the activities. I will update my answer with some example code in a bit, but until then, here is an example: http://stackoverflow.com/questions/3907713/how-to-send-and-receive-broadcast-message – alzee Dec 14 '15 at 11:23
  • Otto library is doing same thing but easier,more readable etc – Adam Fręśko Dec 15 '15 at 21:34