Search code examples
androidgeolocationgpsandroid-location

My GPS provider is enabled but I get null location nonetheless


I'm using this code to get the geo-position of the user

public Location getLocation() {

      Location location = null;
      double lat;
      double lng;
        try {
            LocationManager mLocationManager = (LocationManager) con.getSystemService(LOCATION_SERVICE);

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

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


            if (!isGPSEnabled && !isNetworkEnabled) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            } else {
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,  0,  0, this);
                    Log.d("Network", "Network");
                    if (mLocationManager != null) {
                        location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            lat = location.getLatitude();
                            lng = location.getLongitude();
                            System.out.println(lat);
                        }
                    }
                }
                //get the location by gps
                if (isGPSEnabled) {
                        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (mLocationManager != null) {
                            location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                lat = location.getLatitude();
                                lng = location.getLongitude();
                                System.out.println(lat);
                            }                             
                        }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }



        return location;
    }

An this is what I get:

Network 39.68967 Gps Enabled (nothing)

I can't understand the reason why Gps is enabled and I still can't get the coordinates from the gps provider


Solution

  • I just finished creating a sample project for understanding the usage of Location Services. I am just posting my code, feel free to use it for your need and understanding the working of Location Services.

    public class DSLVFragmentClicks extends Activity implements LocationListener {
    private final int BESTAVAILABLEPROVIDERCODE = 1;
    private final int BESTPROVIDERCODE = 2;
    LocationManager locationManager;
    String bestProvider;
    String bestAvailableProvider;
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == BESTPROVIDERCODE) {
            if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) {
                Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show();
    
            } else {
                getLocation(bestProvider);
            }
        } else {
            if (resultCode!= Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) {
                Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show();
    
            } else {
                getLocation(bestAvailableProvider);
            }
        }
    }
    
    public void getLocation(String usedLocationService) {
        Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show();
        long updateTime = 0;
        float updateDistance = 0;
        // finding the current location 
        locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this);
    
    }
    
    
    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.main);
        // set a Criteria specifying things you want from a particular Location Service
                Criteria criteria = new Criteria();
                criteria.setSpeedRequired(false);
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                criteria.setCostAllowed(true);
                criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
                criteria.setAltitudeRequired(false);
    
                locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
                // finding best provider without fulfilling the criteria
                bestProvider = locationManager.getBestProvider(criteria, false);
                // finding best provider which fulfills the criteria
                bestAvailableProvider = locationManager.getBestProvider(criteria, true);
                String toastMessage = null;
                if (bestProvider == null) {
                    toastMessage = "NO best Provider Found";
                } else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) {
                    boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider);
                    if (!enabled) {
                        Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show();
                        Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE);
                    } else {
                        getLocation(bestAvailableProvider);
                    }
                    toastMessage = bestAvailableProvider + " used for getting your current location";
                } else {
                    boolean enabled = locationManager.isProviderEnabled(bestProvider);
                    if (!enabled) {
                        Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show();
                        Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(mainIntent, BESTPROVIDERCODE);
                    } else {
                        getLocation(bestProvider);
                    }
                    toastMessage = bestProvider + " is used to get your current location";
    
                }
                Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show();
                return true;
            }
        });
    }
    
    @Override
    public void onLocationChanged(Location location) {
        Log.d("Location Found", location.getLatitude() + " " + location.getLongitude());
        // getting the street address from longitute and latitude
        Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
        String addressString = "not found !!";
        try {
            List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            StringBuilder stringBuilder = new StringBuilder();
            if (addressList.size() > 0) {
                Address address = addressList.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    stringBuilder.append(address.getAddressLine(i)).append("\n");
                    stringBuilder.append(address.getLocality()).append("\n");
                    stringBuilder.append(address.getPostalCode()).append("\n");
                    stringBuilder.append(address.getCountryName()).append("\n");
                }
    
                addressString = stringBuilder.toString();
                locationManager.removeUpdates(this);
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show();
    }
    
    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
    
    @Override
    public void onProviderEnabled(String s) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
    
    @Override
    public void onProviderDisabled(String s) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
    }
    

    If you didn't understand any part of it then feel free to ask.