Kemo Kemo - 4 months ago 20
Java Question

Passing location data from fragment to activity in Android

When the user long clicks on a mapFragment I want to send data about the clicked location to another activity, ie. I want to pass lat, long, city, zip code, country... to LocationDetailsActivity.

I successfully passed lat and the long, but I got stuck with everything else. I am a beginner both in coding and android so I use step-by-step examples and so far I couldn't find any step-by-step examples for this.

Code:

if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}

mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

@Override
public void onMapLongClick(LatLng arg0) {

Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> allAddresses = geocoder.getFromLocation(arg0.latitude, arg0.longitude, 1);
if (allAddresses.size() > 0) {
Address address = allAddresses.get(0);
String addressline = allAddresses.get(0).getAddressLine(0);
String city = allAddresses.get(0).getLocality();
String state = allAddresses.get(0).getAdminArea();
String country = allAddresses.get(0).getCountryName();
String postalCode = allAddresses.get(0).getPostalCode();
}

} catch (IOException e) {
e.printStackTrace();
}


Intent intent = new Intent(getActivity(), LocationDetailsActivity.class);
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
intent.putExtra("city",);
intent.putExtra("zip",);
intent.putExtra("country",);
startActivity(intent);

}
});


Any help is appreciated :)

Answer

Try this:

mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng arg0) {

            Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
            try {
                List<Address> allAddresses = geocoder.getFromLocation(arg0.latitude, arg0.longitude, 1);
                  if (allAddresses.size() > 0) {
                    Address address = allAddresses.get(0);

                     Intent intent = new Intent(getActivity(), LocationDetailsActivity.class);
                     intent.putExtra("latitude", arg0.latitude);
                     intent.putExtra("longitude", arg0.longitude);
                     intent.putExtra("city", allAddresses.get(0).getLocality());
                     intent.putExtra("zip", allAddresses.get(0).getPostalCode());
                     intent.putExtra("state", allAddresses.get(0).getAdminArea());
                     intent.putExtra("country", allAddresses.get(0).getCountryName());
                     startActivity(intent);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
Comments