I am using Android Studio and have a method in my MapsActivity that I need to access from another activity. I think using intent is the best way, but I do not know how to.
-
2"I am using Android Studio and have a method in my MapsActivity that I need to access from another activity" -- that is not a good idea, and it is not directly possible. Perhaps these should not be two separate activities, but instead should be a single activity. Or, perhaps this method belongs on some other class, that both activities can access. – CommonsWare Jun 28 '17 at 18:54
3 Answers
This is probably a bad idea. The activity which you would like to invoke the method could be stopped while you are on the second activity, for example. If you need the method, instantiate the class. If the method is refreshing some view on it's activity, you could maybe use "onActivityResult". Otherwise you could create an abstract class and call the method.

- 24
- 8
-
well this is what i need to do... I have a second activity that has a button to take you back to the map, wait for the user to click a specific marker (get the latitude and longitude), and then go back to the second activity. – Krishna Sardana Jun 28 '17 at 19:12
You can do what you want using onActivityResult
.
When you go back to the first Activity you would call startActivityForResult
. Then you put the data in a new intent when the user clicks the marker and finish similar to:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
and then handle the result in your second activity.
More details are here:

- 315
- 4
- 21
EDIT: Based on your comment, and as Felipe Martins pointed out,startActivityForResult()
can work for you.
Use bundle.putDouble
to add lattitude
and longitude
to the bundle and retrieve it later in onActivityResult()
.
Use this for reference: https://stackoverflow.com/a/25642483/4941959

- 160
- 1
- 2
- 9