I would like to get the latitude and longitude from my current location in my app. I am testing on a Galaxy Wi-Fi 5.0. I only need the numbers in double format as I am gonna use it in a google-maps-url. The problem is lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) returns null and i get a nullpointerexception.
private void getLatitudeLongitude()
{
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
showMyAddress(location);
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
showMyAddress(location);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
System.out.println(myLocation.getFromLocation(latitude, longitude, 1).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showMyAddress(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
System.out.println( myLocation.getFromLocation(latitude, longitude, 1).toString());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}