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
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.
Yes. You can call startactivityforresult() from adapter. There are two case- 1. Calling adapter from activity and need onActivityResult in activity.
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.
The two variants of startActivityForResult() method are: public void startActivityForResult (Intent intent, int requestCode) public void startActivityForResult (Intent intent, int requestCode, Bundle options)
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With