Get latitude and longitude for android app (getLastKnownLocation is null)

I would like to get latitude and longitude from my current location in my application. I am testing Galaxy Wi-Fi 5.0. I only need the numbers in double format as I am going to use it in google-maps urls. The problem is that lm.getLastKnownLocation (LocationManager.GPS_PROVIDER) returns null and I get a nullpointer exception.

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();
    }
}

      

+3


source to share





All Articles