0

I have a fragment that opens up a new activity. how can I pass data back to the fragment from that activity when user clicks on back button? I've tried creating a new Intent and put data in there then call setResult(), but neither the Fragment or FragmentActivity got anything in onActivityResult. the only way I can think of now is through static method, but still want to see if there's a proper way of doing this?

Thanks!

user1865027
  • 3,505
  • 6
  • 33
  • 71
  • you can `startActivityForResult()` from activity – N J Oct 06 '15 at 05:00
  • but I already hit back button meaning i wanted to close out that activity. is it necessary to call `startActivityForResult()` ? – user1865027 Oct 06 '15 at 05:02
  • use `startActivityForResult()` and then `setResult` inside activity `onBackPressed()`.. – Anoop M Maddasseri Oct 06 '15 at 05:03
  • see this link http://stackoverflow.com/questions/920306/sending-data-back-to-the-main-activity-in-android – N J Oct 06 '15 at 05:04
  • check this link - http://stackoverflow.com/questions/17085729/startactivityforresult-from-a-fragment-and-finishing-child-activity-doesnt-c – Sino Raj Oct 06 '15 at 05:19
  • weird...how come my `onActivityResult` is called right away when I call `startActivityForResult() ` and pressing the back button doesn't call `onActivityResult` again – user1865027 Oct 06 '15 at 05:43
  • @Muhammad Babar I was thinking about that too but thought there might be some builtin I can utilize. – user1865027 Oct 06 '15 at 06:04
  • @user1865027 The easiest solution is your activity already have the fragment instance use that to pass any data! – Muhammad Babar Oct 06 '15 at 06:09

2 Answers2

1

calling static function and assigning is not a proper solution. you can use interface call back or you can use startActivityForResult() method.

interface callback basic idea ;

public class YourActivity extends Activity{

private MyListener mFragmentCallbackListener; 

  public YourActivity(MyListener listener){
   mFragmentCallbackListener = listener;
  } 

 @Override
 public void onBackPressed(){

 if(mFragmentCallbackListener != null){
   mFragmentCallbackListener.updateFragment(String data);
  }
 }

 public interface MyListener{
  void updateFragment(String data)
 }  
}
droidev
  • 7,352
  • 11
  • 62
  • 94
0

I have a fragment that opens up a new activity

Start your Activity using startActivityForResult() instead of startActivity()

I've tried creating a new Intent and put data in there then call setResult(), but neither the Fragment or FragmentActivity got anything in onActivityResult.

If you are using startActivityForResult() then the onActivityResult() will be called after you finished that Acivity.

uday
  • 1,348
  • 12
  • 27