Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to startActivityForResult from Adapter to get result back to Fragment

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

like image 392
Dan Avatar asked Mar 29 '13 17:03

Dan


People also ask

How can I get result from startActivityForResult?

The android startActivityForResult method, requires a result from the second activity (activity to be invoked). In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.

Can we call startActivityForResult from adapter?

Yes. You can call startactivityforresult() from adapter. There are two case- 1. Calling adapter from activity and need onActivityResult in activity.

How do I pass onActivityResult from activity to fragment?

Since Activity gets the result of onActivityResult() , you will need to override the activity's onActivityResult() and call super. onActivityResult() to propagate to the respective fragment for unhandled results codes or for all.

What are result codes of startActivityForResult?

The two variants of startActivityForResult() method are: public void startActivityForResult (Intent intent, int requestCode) public void startActivityForResult (Intent intent, int requestCode, Bundle options)


2 Answers

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.

like image 135
Biswajit Karmakar Avatar answered Dec 29 '22 14:12

Biswajit Karmakar


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().

like image 34
Adam Nybäck Avatar answered Dec 29 '22 12:12

Adam Nybäck