1

I had tried to send the data from Activity which is instantiated from a Fragment. Sending data from Activity back to fragment. I tried the following code

Fragment:

Instantiated the Fragment
    Intent intent = new Intent(Fragement.this,Activity);
    startActivity(intent);

Activity:

Intent intent = new Intent(Activitiy.this, Fragment);
                intent.putExtra("Sent", "Something");
                setResult(RESULT_OK, intent);
                finish();

Send result to fragment

In Fragment trying to implement onActivityResult but not even able to define the method.
Swamy
  • 65
  • 7

2 Answers2

2

Call your activity using startActivityForResult like below

Intent intent = new Intent(Fragement.this, Activity);
startActivityForResult(intent, 1);

To get the result implement onActivityResult in your fragment

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && requestCode == 1) {
        // here you can retrieve your bundle data.
        String yourdata = data.getStringExtra("Sent");
    }
}

And In your activity do like following.

Intent intent = new Intent();
resultIntent.putExtra("Sent", "String data"); 
setResult(RESULT_OK, intent );
finish();

very important

You must override onActivityResult in your Activity(in which fragment is loaded)

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
    }

For a complete example, see this

Jakir Hossain
  • 3,830
  • 1
  • 15
  • 29
0

you must start the activity with startActviityForResult passing a request code

Intent intent = new Intent(Fragement.this, Activity);
startActivityForResult(intent, myRequestCode);
SebastienRieu
  • 1,443
  • 2
  • 10
  • 20