1

I have an activity and I create a fragment when this activity runs. How do I get the data from the fragment to the activity that creates the fragment?

The part where I create an intent in my activity:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);

    RoutePlansFragment routePlansFragment = RoutePlansFragment.newInstance();
    FragmentTransactionUtil.addFragment(getSupportFragmentManager(), getFragmentContainerId(), routePlansFragment, routePlansFragment.getFragmentTag());

}

This is my fragment:

public static RoutePlansFragment newInstance() {
    RoutePlansFragment routePlansFragment = new RoutePlansFragment();
    return routePlansFragment;
}

How can I send data from this fragment into activity?

fatih
  • 1,285
  • 11
  • 27
  • 1
    Possible Duplicate of https://stackoverflow.com/questions/9343241/passing-data-between-a-fragment-and-its-container-activity – newbieCoder.pkg Sep 24 '18 at 15:11
  • Specifically [this answer](https://stackoverflow.com/a/9977370/1219389), the accepted one isn't a good idea as it leads to tightly coupled code. – PPartisan Sep 24 '18 at 15:23

1 Answers1

0

you can use a callback

in your fragment you have to create a listener

public interface DataListener{
    void sendData(String data);
}

create a reference

    private DataListener mDataListener;

and in onAttach you have to caste your activity as DataListener

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof DataListener) {
        mDataListener = (DataListener) context;
    }
}

your activiy must implements DataListener

and u can send data from fragment by calling sendData method

Ahmed.ess
  • 265
  • 3
  • 10