Вопрос

I am trying to get a current location using the GPS.

Given the following code:

    LocationManager manager = (LocationManager)this.
            getSystemService(Context.LOCATION_SERVICE);

    Location loc = manager.getLastKnownLocation(
            LocationManager.GPS_PROVIDER);

    loc=manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    double la=loc.getLatitude();
    double lon=loc.getLongitude();

When using the AVD emulator with defined fix coordinates, or when tested with my android smartphone, it does not work.

While in Android Studios trying to debug it with the emulator, it get stuck on the loc.getLatitude. Overall, at the end, I got a Java RuntimeException as shown below:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.social.gps/com.example.social.gps.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
        .
        .
        .

I guess its because the loc reference is null.

I have:

<uses-permission
    android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
    android:name="android.permission.ACCESS_COARSE_LOCATION" />

in the manifest.

So how can I get it to work?

Это было полезно?

Решение

Have DDMS prespective and send the latitude and longitude manually to the emulator.Because emulator doesn't retrieve the location status

Другие советы

This is because your loc variable is null - it happens when there are no last location in the cache.

getLastKnownLocation() doesn't return the current location, it returns location obtained previously by your or some other app. To receive current location, you need to subscribe for location updates using locationManager.requestLocationUpdates(). That will start mentioned provider (GPS, Network or Passive) if it is enabled by user and send location updates via callback.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top