2013-10-27 5 views
15

Avevo appena funzionato, ma quando ho spento il mio Wifi per vedere se potevo ottenere una posizione più precisa usando il mio GPS ora mi porta un errore NullPointer e non riesco a capire perché.getLastKnownLocation restituisce NULL

Il codice seguente viene chiamato per primo;

public void onConnected(Bundle dataBundle) { 
     connected = true; 
     //Request an update from the location client to get current Location details 
     mLocationClient.requestLocationUpdates(mLocationRequest,this); 
     Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); 
    } 

Che poi comporta questo metodo viene chiamato

public void onLocationChanged(android.location.Location location) { 
     // Report to the UI that the location was updated 
     String msg = "Updated Location: " + 
       Double.toString(location.getLatitude()) + "," + 
       Double.toString(location.getLongitude()); 
     if(tmp != location.getLatitude()) 
     { 
      Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 
     } 
     tmp = location.getLatitude(); 
    } 

Potete vedere Ho 2 toast lì e tornano bene con le coordinate effettive GPS, ma quando chiamo il codice qui sotto si blocca su la nuova linea di ubicazione getLastKnownLocation

public String getLocation() 
    { 
     // Get the location manager 
     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     Criteria criteria = new Criteria(); 
     String bestProvider = locationManager.getBestProvider(criteria, false); 
     android.location.Location location = locationManager.getLastKnownLocation(bestProvider); 
     Double lat,lon; 
     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
     Date date = new Date(); 
     try { 
      lat = location.getLatitude(); 
      lon = location.getLongitude(); 
      Toast.makeText(this,""+lat.toString()+"-"+lon.toString(),Toast.LENGTH_SHORT).show(); 
      return new LatLng(lat, lon).toString(); 
     } 
     catch (NullPointerException e){ 
      Toast.makeText(this,"HELL-NO",Toast.LENGTH_SHORT).show(); 
      Log.e("HELL-NO","n",e); 
      e.printStackTrace(); 
      return null; 
     } 
    } 

io proprio non capisco il motivo per cui quando si tenta di recuperare la posizione, che sembra essere stata recuperata nelMetodo, si tratta solo di un punto nullo.

+0

si stia mescolando nuove API e vecchio per getLastLocation seguire questa https://stackoverflow.com/a/48033659/4997704 –

risposta

7

stai mescolando insieme le nuove e le vecchie API di posizione quando non dovresti.

per ottenere l'ultima posizione nota tutto il vostro hanno a che fare è chiamare

mLocationClient.getLastLocation(); 

una volta che il servizio di localizzazione è stato collegato.

leggere come utilizzare la nuova posizione API

http://developer.android.com/training/location/retrieve-current.html#GetLocation

+1

Acclamazioni @tyczj, non sapeva ci era una "nuova" API, grazie ancora! – r0bb077

27

Ho semplicemente cambiato

locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) to 
locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 

Questa risolto la soluzione per me. Snippet completo:

map = ((MapFragment) getFragmentManager(). 
      findFragmentById(R.id.map)).getMap(); 

    map.setMyLocationEnabled(true); 

    locationManager = (LocationManager)getSystemService 
      (Context.LOCATION_SERVICE); 
    getLastLocation = locationManager.getLastKnownLocation 
      (LocationManager.PASSIVE_PROVIDER); 
    currentLongitude = getLastLocation.getLongitude(); 
    currentLatitude = getLastLocation.getLatitude(); 

    currentLocation = new LatLng(currentLatitude, currentLongitude); 

Spero che questo aiuti.

+2

funziona per me ma qual è la differenza tra GPS_PROVIDER e PASSIVE_PROVIDER? –

+0

@aishwatsingh http://stackoverflow.com/a/5655329/3878508 –

+0

@TroyZuroske Qualche idea sul perché il provider passivo risolva questo problema? Ci scusiamo per l'urto. Ha funzionato anche per me, grazie! –

0

Ho lottato con questo per molto tempo. Ma Google ha appena trovato una soluzione.

googleMap.getMyLocation(); 

per ottenere la posizione del punto blu su api V2.

0

provare questo codice:

LocationManager mLocationManager; 
Location myLocation = getLastKnownLocation(); 

private Location getLastKnownLocation() { 
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE); 
    List<String> providers = mLocationManager.getProviders(true); 
    Location bestLocation = null; 
    for (String provider : providers) { 
     Location l = mLocationManager.getLastKnownLocation(provider); 
     if (l == null) { 
      continue; 
     } 
     if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { 
      // Found best last known location: %s", l); 
      bestLocation = l; 
     } 
    } 
    return bestLocation; 
}