Abdur Rahman
Abdur Rahman

Reputation: 1001

Android : How to efficiently send and receive data between Fragment and Activity?

I'm using two fragments in my activity using ViewPager and TabLayout. I want to send and receive data between my Activity and my Fragments.

I don't prefer to use a class with static variables to fix this problem. Is there a better way to do this task with out loosing much memory and resources. Because static data members never die in the whole life cycle of app. So they never release any chunk of memory. Which is a big problem for app to run in Samsung devices or you can say non rooted devices who restrict the usage of RAM.

Upvotes: 0

Views: 114

Answers (3)

chari sharma
chari sharma

Reputation: 482

Here is an example of Fragment to Activity communication:

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");
    }
}

}

Upvotes: 1

Umut ADALI
Umut ADALI

Reputation: 1196

You can do it in 2 ways. First method is define a interface. interface example Second method is eventbus. eventbus library

My preference eventbus. Even if possible, learn rxjava and do it with the event logic there. Rxjava tutorial

Upvotes: 1

Shobhit Puri
Shobhit Puri

Reputation: 26007

Use Interface. Here is an excerpt from Android doc which contains details with examples of how to communicate between Fragment and Activity and vice versa: Define an Interface.

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. 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.

This makes your Fragment modular and allows you to reuse the same Fragment in multiple activities. All you would need to do is implement the interface in the new Activity.

Upvotes: 3

Related Questions