tags:

views:

434

answers:

4

dear friends, i am trying to get current latitude and longitude and written following code given exception at getlatitude method

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) {
    }
    }

how to solve this issue

manifest file

A: 

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

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

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
do i need to install something else to activate gps??
UMMA
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
A: 

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.

dtmilano
could you please elebrate this what does it mean menu-> my location so that i could solve this problem?
UMMA
(touch) google maps app (icon) -> (press) Menu (button) -> (touch) My Location (icon)
dtmilano
A: 

finally got the answer myself...

http://stackoverflow.com/questions/2279647/how-to-get-gps-location-in-android

UMMA