So I followed an answer to this question:
I tried to integrate it into my code, but it doesn't work.
Basically I want to get the current coordinates and then submit them to an email adress.
This is from an answer and should get the coordinates and write them into the variables 'lat' and 'lon'
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
Then I try to send an email, when the button is clicked. This will open the email application. But the app should write all the text herself. (Can I simple send it in the background too?) In the body there should be a little text and then my coordinates, which I defined in the variables 'lat' and 'lon'. Sadly it doesn't recognise my variables. What do I have to change?
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getLocation();
Intent i = new Intent(Intent.ACTION_SENDTO);
//i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mailadress@example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , lat + lon);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MapsActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
Edit
This is the error in the stacktrace:
08-07 09:59:58.339 31371-31371/com.example.testingmapingmarker23 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testingmapingmarker23, PID: 31371
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, com.android.systemui=overlay:system, com.android.systemui.navbar=overlay:system}
java.lang.NullPointerException: Attempt to read from field 'double com.google.android.gms.maps.model.LatLng.latitude' on a null object reference
at com.example.testingmapingmarker23.MapsActivity$1$1.onClick(MapsActivity.java:91)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)