2

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 = currentLocation.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>
Siddharth
  • 9,349
  • 16
  • 86
  • 148
UMAR-MOBITSOLUTIONS
  • 77,236
  • 95
  • 209
  • 278

4 Answers4

4

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.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
1

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

<uses-permission 
    android:name="android.permission.ACCESS_FINE_LOCATION" />
Maurits Rijk
  • 9,789
  • 2
  • 36
  • 53
1

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.

Jorge Córdoba
  • 51,063
  • 11
  • 80
  • 130
  • do i need to install something else to activate gps?? – UMAR-MOBITSOLUTIONS Feb 08 '10 at 08:13
  • From the emulator, when running, go to your DDMS perspective(it's called like this right?), select the 'Emulator Control' tab and you will see a 'Location Control' part where you can send latitude/longitude positions – ccheneson Feb 08 '10 at 13:25
1

finally got the answer myself...

How to emulate GPS location in the Android Emulator?

Community
  • 1
  • 1
UMAR-MOBITSOLUTIONS
  • 77,236
  • 95
  • 209
  • 278