问题
I got the following code. I'm trying to submit my coordinates to an email.
But every time I press the button, the app closes.
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();
Log.i("logging","lat "+lat+" long "+lon);
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LatLng latlng = 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 , latlng.latitude+" " + latlng.longitude);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
makeText(MapsActivity.this, "There are no email clients installed.", LENGTH_SHORT).show();
}
}
});
}
});
If I press the button, the following error from the stack trace appears:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testingmapingmarker23, PID: 6630
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:96)
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)
So the question is: what is exactly the problem? Somehow the coordinates are not shown through the Log too.
回答1:
You should null check the latlng
before any action you want to perform on this object.
e.g.
LatLng latlng = 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");
if(latlng != null) {
i.putExtra(Intent.EXTRA_TEXT , latlng.latitude+" " + latlng.longitude);
} else {
i.putExtra(Intent.EXTRA_TEXT , "location not available");
}
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
makeText(MapsActivity.this, "There are no email clients installed.", LENGTH_SHORT).show();
}
回答2:
This code only gives you the LastKnownLocation that too if the location is stored in the device. It does not give you the most current location necessarily all the time. If you need to get the Location, you need to perform certain steps.
- Request Permission to Access Location - ACCESS_FINE_LOCATION
- Create a Location Manager class that implements
android.location.LocationListener
- Initiate the Location Service using
(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
- Check for Last known Location as you have done above.
- If its not available request for the current location using
requestLocationUpdates()
listener method. - Implement
onLocationChanged()
method and get the current location in that method. - Perform your operation once the location is received.
- Disable the listener once the work is done.
You can follow the below mentioned links to see how the above steps work out.
https://www.codota.com/android/scenarios/52fcbdd6da0a6fdfa462fe3b/finding-current-location?tag=dragonfly&fullSource=1
https://www.tutorialspoint.com/android/android_location_based_services.htm
http://javapapers.com/android/get-current-location-in-android/
来源:https://stackoverflow.com/questions/45542559/app-closes-while-it-should-submit-data