Android: setResult not working

Scenario: I have MainActivity.java , OtherPageForFragments.java and a fragment that is on OtherPageForFragments.java

In MainActivity.java , I wrote the following code to start an action and get the result in

onActivityResult (int requestCode, int resultCode, Intent data)

is an

 startActivityForResult(new Intent(this, OtherPageForFragments.class),REQUEST_CODE_MAP); 

In the onDestroy() of the fragment class, I wrote 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 to get the result in the MainActivity class. So, I wrote 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); } 

Problem: returning resultCode not Activity.RESULT_OK , but Intent I get null .

What to do? Thanks

+8
java android android-intent
source share
3 answers
 getActivity().setResult(Activity.RESULT_OK, intent); getActivity().finish(); 

this code should not be in onDestroy. onDestroy happens after the activity is already completed, and onActivityResult is called.

this code should be in the code that closes the activity / fragment, for example, on the back key pressed or the close button onClick

+9
source share

You may need to clarify startup modes for both activities. usually they should be "standard" if there are "singleTop" attributes in the activity manifest file ....... you need to pay more attention.

+4
source share

Try the following:

 Intent data = new Intent(); intent.putExtra("Latitude", passLatLng.latitude); intent.putExtra("Longitude", passLatLng.longitude); if (getParent() == null) { setResult(Activity.RESULT_OK, data); } else { getParent().setResult(Activity.RESULT_OK, data); } getActivity().finish(); 
+3
source share

All Articles