Kemo Kemo - 5 months ago 40
Android Question

Passing lat lng to another activity in Android

I am trying to enable the user to long click on a map and, instead of creating a marker, the new activity should open. It should contain latitude and longitude, i.e. the location on which the user clicked.

I know data transfer is easy when I use dialogs, but I don't want to use dialog fragment in this part of my app.

MapActivity:

//Add marker on long click
final double finalLongitude = longitude;
final double finalLatitude = latitude;

mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
// start SendMessageActivity need to add marker to message activity
Intent intent = new Intent(getActivity(), DisplayLocationActivity.class);
intent.putExtra("latitude",""+ finalLatitude);
intent.putExtra("longitude", "" + finalLongitude);
startActivity(intent);
}


DisplayLocationActivity:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_location);

Bundle bundle = getIntent().getExtras();
double lat = bundle.getDouble("latitude");
double lng = bundle.getDouble("longitude");

//display lat lng
mLatDisplay = (TextView) findViewById(R.id.latTextViewDisplay);
mLangDisplay = (TextView) findViewById(R.id.lngTextViewDisplay);

mLatDisplay.setText(String.valueOf(lat));
mLangDisplay.setText(String.valueOf(lng));
}


My problem is this - when I start the app and click on the map, the newly opened activity displays the lat and lng as 0.0 no matter where on the map I clicked.

Answer

As see here LatLng:

public final class LatLng extends Object implements Parcelable

Means Latlng class implements Parcelable interface, so we can pass it direclty using Intent.putExtra like:

@Override
public void onMapLongClick(LatLng arg) {
  intent.putExtra("Latlng", arg);
  ..
}

and get it in next Activity using getExtras().getParcelable like:

LatLng objLatLng=getIntent().getExtras().getParcelable("Latlng");

Now use objLatLng to show location coordinates in TextView's.

Comments