0

I am trying to find out current latitude and longitude of android device but I am getting java.lang.nullpointerexception and app is force closing.even though i get refrence from here and used the code from the answer which was accepted as correct: How to get Android GPS location my code is:

try{
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
             Criteria criteria = new Criteria();
             String bestProvider = locationManager.getBestProvider(criteria, false);
             Location location = locationManager.getLastKnownLocation(bestProvider);


        double latit=location.getLatitude();
        double longit=location.getLongitude();
        Toast.makeText(getApplicationContext(),"Your Location is:\nLatitude:\t"+latit+"\nLongitude:\t"+longit,Toast.LENGTH_LONG).show();
            }catch(Exception ex){
                Toast.makeText(getApplicationContext(), "Error:"+ex,Toast.LENGTH_LONG).show();
            }
Community
  • 1
  • 1
Kme
  • 103
  • 1
  • 11

2 Answers2

0

I would bet that your location variable is null and that's why you're getting the NullPointerException. When you call LocationManager.getLastKnownLocation() it can return null if there is no last known location. Your best bet is to request location updates using one of the LocationManager.requestLocationUpdates() methods and passing in a LocationListener.

CaseyB
  • 24,495
  • 12
  • 73
  • 109
  • I have never used this method.please show me how to use this. – Kme May 28 '14 at 18:20
  • The best example that I could recommend come from Reto Meier's blog. http://android-developers.blogspot.de/2011/06/deep-dive-into-location.html – CaseyB May 28 '14 at 18:23
0

you can use the gps tracker class to get current location

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = (1000 * 60 * 1)/6; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,   this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {

    final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setMessage(
            "Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(true)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()

            {
            public void onClick(final DialogInterface dialog,
                        final int id) {
            Intent intent = new Intent(                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);

                }
            });

    final AlertDialog alert = builder.create();

    alert.show();

}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

now in your activity:

make a object of gps tracker class

 GPSTracker gps = new GPSTracker(youractivity.this);
 double _mylats = gps.getLatitude();
 double _mylongs = gps.getLongitude();
Pankaj Arora
  • 11,041
  • 2
  • 38
  • 62