Reputation: 42710
Note, this is an official way for Fragment
to Activity
communication, according to http://developer.android.com/training/basics/fragments/communicating.html
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onArticleSelected(position);
}
}
However, I had came across code which performs the following technique.
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
((OnHeadlineSelectedListener)this.getActivity()).onArticleSelected(position);
}
I tested so far it works, even after configuration change, I still get the latest Activity
.
I just wondering, is there any catch behind this method, besides method recommended by Google? For instance, can getActivity
even return null?
Upvotes: 2
Views: 368
Reputation: 13967
An advantage of the official way is, that you have only one location in your code where you need to ensure that the activity implements the interface(s). In the second approach, if you want avoid any ClassCastExceptions
, you have to catch ClassCastExceptions after every method call.
Though I used the second approach often too (without any issues), I can imagine that it's beneficial to use Googles version in particular in case of many method calls, lots of interfaces or rather big projects where parts (fragments and activities) are delivered by different teams.
Upvotes: 1
Reputation: 30944
You should be fine with the second way - the first way is basically a "shortcut", that stores the activity in a local variable instead of "fetching" it via getActivity()
each time it is used.
Upvotes: 2