FirstActivity.Java
has a FragmentA.Java
which calls startActivityForResult()
.
SecondActivity.Java
call finish()
but onActivityResult
never get called which is
written in FragmentA.Java
.
FragmentA.Java
code:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// some code
Intent i = new Intent(getActivity(), SecondActivity.class);
i.putExtra("helloString", helloString);
getActivity().startActivityForResult(i, 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
getActivity();
if(requestCode == 1 && resultCode == Activity.RESULT_OK) {
//some code
}
}
SecondActivity.Java
code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
I have tried debugging the code, but onAcitvityResult()
never get called.
You must write onActivityResult() in your FirstActivity.Java as follows
This will trigger onActivityResult method of fragments on FirstActivity.java
The fragment already has
startActivityForResult
, which would callonActivityResult
in the fragment if you use it, instead ofgetActivity()
...We could call
startActivityForResult()
directly from Fragment So You should callthis.startActivityForResult(i, 1);
instead ofgetActivity().startActivityForResult(i, 1);
Activity will send the Activity Result to your Fragment.
onActivityResult() of MAinActivity will call , onActivityResult() of Fragement wont call because fragment is placed in Activity so obviously it come back to MainActivity
Kevin's answer works but It makes it hard to play with the data using that solution.
Best solution is don't start
startActivityForResult()
on activity level.in your case don't call
getActivity().startActivityForResult(i, 1);
Instead, just use
startActivityForResult()
and it will work perfectly fine! :)The most important thing, that all are missing here is... The launchMode of FirstActivity must be singleTop. If it is singleInstance, the onActivityResult in FragmentA will be called just after calling the startActivityForResult method. So, It will not wait for calling of the finish() method in SecondActivity.
So go through the following steps, It will definitely work as it worked for me too after a long research.
In AndroidManifest.xml file, make launchMode of FirstActivity.Java as singleTop.
In FirstActivity.java, override onActivityResult method. As this will call the onActivityResult of FragmentA.
In FragmentA.Java, override onActivityResult method
Call
startActivityForResult(intent, HOMEWORK_POST_ACTIVITY);
from FragmentA.JavaCall
finish();
method in SecondActivity.javaHope this will work.