15

I want to send String data from fragment to activity.

I have read the article about communicating between fragment and activity in android developer, using onAttach callback.

can anyone explain clearly how to send data from fragment to activity?

Orkun
  • 6,998
  • 8
  • 56
  • 103
user1526671
  • 817
  • 4
  • 16
  • 33

1 Answers1

37

You should do something like this. First create an interface which will use to comunicate with your activity for example :

public interface OnViewSelected {
public void onViewSelected(int viewId);
}

and in your onAttach do this :

OnViewSelected _mClickListener;
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        _mClickListener = (OnViewSelected) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement onViewSelected");
    }
}

In your Fragment implement OnClickListener and in your onClick() method do this :

@Override
public void onClick(View v) {
    _mClickListener.onViewSelected(456);
}

After that in your Activity you have to implement the interface you created in your Fragment and it will ask you to add unimplemented methods and in your activity you will have function like this :

@Override
public void onViewSelected(int data) {
    Log.d("","data : "+data); // this value will be 456.
}

That's all. : )

hardartcore
  • 16,886
  • 12
  • 75
  • 101
  • 2
    nice :) Android Framework generates like as you say. And I now can understand it clearly – hqt Nov 06 '13 at 04:49
  • why to create an interface ? Can't you just create a context ctx (global) , and cast it the activity passed inside onAttach by ctx = (YourActivity) activity, and then use ctx.onViewSelected(data), given ofCourse you have created onViewSelected in your Activity. – tony9099 Dec 26 '13 at 20:59
  • Because in my opinion this is the best way so far,doesn't matter if I use this in one `Fragment` or lots of. Your implementation will work too, but I like interfaces more :) – hardartcore Dec 27 '13 at 06:03
  • 5
    @tony9099 the reason for creating the interface (and why the android tutorials explain it that way) is to ensure that your fragment is re-usable and therefore do not depend on that specific Activity but rather a component that implement that listener. – Thomas Jan 17 '14 at 12:39
  • 1
    as of now `public void onAttach(Activity activity)` is officially deprecated. – guness Aug 25 '15 at 11:14
  • @bluebrain so you can use `public void onAttach(Context context)`. – hardartcore Aug 25 '15 at 15:26
  • Question - is it does not provide memory leak? Or should I in onDetach release the callback? – Sirop4ik Feb 11 '19 at 11:27
  • @AlekseyTimoshchenko you can release the callback just in case. – hardartcore Feb 11 '19 at 12:12