9

I have several Fragments with custom ListViews. They use my custom ListAdapter, in which i handle clicks on list's elements. I need to start another activity from this OnClickListener and get some information back to Fragment. i try to use

Intent intent=new Intent(context, DataFillerActivity.class);  
((Activity) context).startActivityForResult(intent, 3);

but DataFillerActivity returns result to MainActivity, not to Fragment. so what is the best way to solve this problem ? thanks

Kirk
  • 16,182
  • 20
  • 80
  • 112
Dan
  • 108
  • 1
  • 1
  • 7

4 Answers4

9

Make onActivityResult method in Main Activity like this

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        // Check if image is captured successfully

        super.onActivityResult(requestCode, resultCode, data);
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }

It will pass the result code to its child fragment.

Biswajit Karmakar
  • 9,799
  • 4
  • 39
  • 41
5

As Steve writes, a fragment should be modular. However, this means that the communication should not go through any activity but stay within the fragment.

To solve this, make sure your ListAdapter has a reference to the fragment and use fragment.startActivityForResult(). Then the result will come back to the fragment's onActivityResult().

Adam Nybäck
  • 845
  • 7
  • 13
  • Tried but not working, not sure is it due to bug related to http://stackoverflow.com/questions/18271761/onactivityresult-gets-called-when-activity-starts-not-when-its-finished. But if I call another activity from my fragment, it does works. Only when the startActivityForResult is called within the ListView of the fragment, the onActivityResult of the fragment get called immediately right after the intended activity started. – TPG Jun 17 '15 at 03:39
  • I solved my problem after removing intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); before calling fragment.startActivityForResult(intent, 0); +1 for you. – TPG Jun 17 '15 at 04:35
3

To update your fragment, the only way should be over the activity. Thats because a Fragment is designed to be modular.

http://developer.android.com/training/basics/fragments/communicating.html

If you start an Acitivity for result, the result will be passed to the Activity which started the request. Now you can pass the Data to your desired Fragment.

Steve Benett
  • 12,843
  • 7
  • 59
  • 79
2

just override the onActivityresult in your Activity class and pass the result the the fragment from the activity, you can find fragment either but id your tag

Kapil Vats
  • 5,485
  • 1
  • 27
  • 30