2013-04-14 7 views
21

Recentemente, ho creato una semplice applicazione per ottenere la posizione GPS e la visualizzazione sul telefono Android. All'inizio sono riuscito a ottenere la posizione dopo qualche tentativo, ma dopo aver reinstallato il file apk, getLastKnownLocation() restituisce sempre un valore null. ambientegetlastknownlocation restituisce sempre null dopo aver reinstallato il file apk tramite eclipse

sviluppo usato: - API 10 gingerbread 2.3.6 - fornitore di GPS viene usato

sotto è il codice ho applicato nel mio progetto 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(); 
      } 

     } 
    } 

Qualcuno può suggerire una possibile soluzione risolvere il valore nullo restituito da getLastKnownLocation()? Qualsiasi aiuto sarà apprezzato. Grazie.

risposta

42

il getLastKnownLocation() questo restituisce l'ultima posizione nota ... dopo si ri-installare l'applicazione non avrà alcun ultima posizione nota ... in modo che si tradurrà in NPE ... invece utilizzare il codice qui sotto

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; 
} 

Ha funzionato per me ... dovrebbe funzionare anche per te ...

+0

Grazie. Questo ha risolto il problema. – Student

+0

È un grande codice. Molte grazie. –

+15

Non è un gran bel codice ... mettere tutto il codice in un try/catch senza che ne abbia esplicitamente bisogno è una cattiva programmazione in linea di principio. Se vuoi davvero un bel pezzo di codice, prova questo: https://web.archive.org/web/20100429083435/http://marakana.com/forums/android/android_examples/42.html –

1

Hai solo bisogno di aggiungere più di una riga nel codice

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

cosa succede se posizione == null?Come ottenere la posizione esatta –

+0

attendere cosa non va con te, non so esattamente cosa stai cercando di rispondere. La domanda è qui per qualcuno che gli dica una soluzione, come liberarsi di questo oggetto nullo che viene restituito sul metodo getLastKnownLocation (PROVIDER). Non mostrare un messaggio di brindisi, senza alcun suggerimento su cosa fare dopo. – Khay

0

Prova seguente codice

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()); 
+1

Non risponde al problema. –

-1

Ho avuto lo stesso problema dopo la reinstallazione tramite eclipse. Ho risolto le impostazioni Android/Sicurezza/permessi dell'app e confermato le autorizzazioni di posizione all'applicazione.

+2

Questo non è il modo in cui è necessario chiedere all'utente di concedere tali autorizzazioni in runtime. [per maggiori informazioni controlla questo] (https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous) – kId

1

Questa soluzione è il mio piccolo miglioramento per il codice @ 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(); 
    } 

Godetevi

Problemi correlati