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.
si stia mescolando nuove API e vecchio per getLastLocation seguire questa https://stackoverflow.com/a/48033659/4997704 –