Scenario: I have a MainActivity.java
, OtherPageForFragments.java
and a fragment which is on OtherPageForFragments.java
In MainActivity.java
, I have written the following code to start an activity and get result in
onActivityResult(int requestCode, int resultCode, Intent data)
is
startActivityForResult(new Intent(this, OtherPageForFragments.class),REQUEST_CODE_MAP);
In the onDestroy()
of the fragment class, i have written this:
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
mlocManager.removeUpdates(this);
Intent intent = new Intent();
intent.putExtra("Latitude", passLatLng.latitude);
intent.putExtra("Longitude", passLatLng.longitude);
getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();
}
Now, I want my result in the MainActivity
class. So, i have written the following code in the onActivityResult
method:
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_MAP)
{
tost("2");
double lat=data.getExtras().getDouble("Latitude");
double lng=data.getExtras().getDouble("Longitude");
tost(lat + " -- " + lng);
}
The Problem: the resultCode
getting returned is not Activity.RESULT_OK
and the Intent
I am getting is null
.
What to do? Thanks
By the help of android startActivityForResult() method, we can get result from another activity. By the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa.
registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you'll use to launch the other activity. An ActivityResultContract defines the input type needed to produce a result along with the output type of the result.
The setResult method takes an int result value and an Intent that is passed back to the calling Activity. Intent resultIntent = new Intent(); // TODO Add extras or a data URI to this intent as appropriate. resultIntent. putExtra("some_key", "String data"); setResult(Activity.
getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();
this code shouldn't be in onDestroy. onDestroy happens after the activity is already finished, and onActivityResult was called.
this code needs to in the code that closes the activity/fragment, like on back key pressed, or a close button onClick
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