开发者

how to solve Null pointer exception on Getting latitude or GPS?

开发者 https://www.devze.com 2022-12-19 06:13 出处:网络
I am trying to get current long, lat. I am getting a Nullpointer on LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

I am trying to get current long, lat. I am getting a Nullpointer on LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener myLocationListener = new CurrentLocationListener(); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, myLocationListener);
    Location currentLocation = locationManager.getLastKnownLocation("gps"); 
    Latitude = currentLocation.getLatitude();  ----->>> null pointer exception here
    Longitude = curren开发者_如何学GotLocation.getLongitude();

public class CurrentLocationListener implements LocationListener{
    public void onLocationChanged(Location argLocation) {
    }
    public void onProviderDisabled(String provider) {
    }
    public void onProviderEnabled(String provider) {
    }
    public void onStatusChanged(String provider, int status, Bundle arg2) {
    }
} 

My manifest file

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


This is usually because there's no last know location. To force obtaining the location you can register for location updates and wait or you can launch google maps application, obtain the location using Menu -> My Location, return to your application and last know location shouldn't be null.


Did you set the right permissions in the manifest file? Something like:

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


Kind of obvious ...

Location currentLocation = locationManager.getLastKnownLocation("gps"); 

if (currentLocation != null)
{
    Latitude = currentLocation.getLatitude();
    Longitude = currentLocation.getLongitude();
}

Now, about WHY locationManager is returning a null references instead of an actual Location reference ... It's difficult to know with the code provided. Could be anything.

Edit: Mmm, seems like it could be that you have no gps fix yet.


finally got the answer myself...

How to emulate GPS location in the Android Emulator?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号