Sunday, February 17, 2013

Fragments Tutorial - Simple 2 - Passing Data

Passing Data between Fragment and host Activity

To pass data from a Fragment to the host Activity we need to Define/declare an Interface and
Implement it on the Activity.

1. Declare an Interface on Fragment_A. 

public interface OnSomethingSelectedListener {
    public void passData(int position);

2. onAttach() : To be sure that Activity implements the Interface  onAttach callback method of Fragment_A  we instantiate an Instance of Ιnterface by casting the Activity  passed into onAttach().
The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.

    public void onAttach(Activity activity) {
        // This makes sure that the container activity has implemented the callback interface. If not, it throws an exception
        try {
            listener = (OnSomethingSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");

3. On Main Activity we implement the Interface like this :

public class MainActivity extends FragmentActivity implements OnSomethingSelectedListener

public void passData(int position) {
 Log.d(TAG, "Give me the result  " + position  );
 position = position +1;
 Log.d(TAG, "Give me the result  " + position  ); 

We just take the integer value parameter from the Fragment and add one to it.

4. A button on Fragment's layout so we can add onClick event

android:text="send Integer">

5. And on Fragment's onCreateView() we add the listener for the event:
Button button = (Button) view.findViewById(;
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.v(TAG, "onClick 1");
            listener.passData(5); //pass an Integer
We pass the value five to the method passData() Now when we click on the Button we open LogCat View and we see that value one has been added to the  value  of the parameter:

1 comment:

  1. Hi, great post but i expects a more help can you send a full example on, will be waiting for the reply