web-dev-qa-db-fra.com

getlastknownlocation renvoie toujours la valeur null après avoir réinstallé le fichier apk via eclipse

Récemment, j'ai créé une application simple pour obtenir l'emplacement GPS et l'affichage sur un téléphone Android . Au début, je pouvais obtenir l'emplacement après quelques essais, mais après avoir réinstallé le fichier apk, getLastKnownLocation () renvoie toujours valeur nulle.

Environnement de développement utilisé: - API 10 Gingerbread 2.3.6 - Le fournisseur GPS est utilisé

voici le code que j'ai appliqué dans mon projet Android:

        public class MyActivity extends MapActivity{
protected void onCreate(Bundle savedInstanceState) {


    mapView = (MapView)findViewById(R.id.myTripMap);
    mapController = mapView.getController();
    mapView.setSatellite(false);
    mapView.setStreetView(true);
    mapView.displayZoomControls(false);
    mapView.setBuiltInZoomControls(true);//
    mapView.setClickable(true);
    mapController.setZoom(14);      


    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    provider = locationManager.getBestProvider(criteria, true);
    location = locationManager.getLastKnownLocation(provider);

    updateMyCurrentLoc(location);

    locationManager.requestLocationUpdates(provider, 2, 1,locationListener);



}


          private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          updateMyCurrentLoc(location);
        }

        public void onProviderDisabled(String provider){
          updateMyCurrentLoc(null);
        }

        public void onProviderEnabled(String provider){ }
        public void onStatusChanged(String provider, int status, 
                                    Bundle extras){ }
      };


      private void updateMyCurrentLoc(Location location) {



            if (location != null) {

             // other codes to get the address and display
            Toast.makeText(getBaseContext(), "provider used : "+provider).show();   //testing purpose
            } 
            else {
              str = "No location found";
              Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
            }

        }
    }

Quelqu'un peut-il suggérer une solution possible pour résoudre la valeur null renvoyée par getLastKnownLocation ()? Toute aide sera appréciée. Merci.

24
Student

la getLastKnownLocation() ceci retourne le dernier emplacement connu ... après avoir réinstallé l'application, il n'aura plus de dernier emplacement connu ... il en résultera un NPE ... à la place, utilisez le code ci-dessous 

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 Enabled");
                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", "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;
}

Cela a fonctionné pour moi ... devrait fonctionner pour vous aussi ...

44
Karan Mer

Cette solution est ma petite amélioration pour le code @Karan Mer.

    public Location getLocation() {
    int MIN_TIME_BW_UPDATES = 10000;
    int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10000;
    try {
        locationManager = (LocationManager) getApplicationContext()
                .getSystemService(LOCATION_SERVICE);

        boolean isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        boolean isPassiveEnabled = locationManager
                .isProviderEnabled(LocationManager.PASSIVE_PROVIDER);

        boolean isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isGPSEnabled || isNetworkEnabled || isPassiveEnabled) {

            this.canGetLocation = true;
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled && location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
            }
            if (isPassiveEnabled && location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.PASSIVE_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                }
            }

            if (isNetworkEnabled && location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }

        }else{
            return null;
        }

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

Prendre plaisir

1
Davido

Essayez de suivre le code

LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);

    String locationProvider = LocationManager.NETWORK_PROVIDER;
    Location lastlocation = locationManager.getLastKnownLocation(locationProvider);

    String CurLat = String.valueOf(lastlocation.getLatitude());
    String Curlongi= String.valueOf(lastlocation.getLongitude());
0
Dhanveer thakur

Il vous suffit d'ajouter une ligne de plus dans le code

if (locationManager != null) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

    } else {
        Toast.makeText(
                mContext,
                "Location Null", Toast.LENGTH_SHORT).show();
    }
}
0
Shirish Shinde