Android : Google API - NULL Pointer by getLastKnownLocation

on Saturday, September 13, 2014


Yesterdy my App worked perfectly but this morning it began to crash. I think the trigger was that I rebooted my Smartphone , so my APP loosed the GPS datas. I started the Debug mode and looked step by step for NULL values and I actuelly find it by this command :



myLocation = locationManager.getLastKnownLocation(provider);


This returns a NULL object which cause to an crash when I try to use these methods :



latitude = myLocation.getLatitude();
longtitude = myLocation.getLongitude();


How can I make that my Location is not NULL in this case ? I tried to use the NETWORK_PROVIDER but then I have to use the WLAN and this is not the best way I think.Can I still catch informations with the GPS_PROVIDER without to get into a other Application which save them ?


BTW here is my Code :



public class gmapps extends FragmentActivity {

private GoogleMap googleMap;
TextView txt_street , txt_city , txt_country ;
Geocoder geocoder;
List<Address> addresses;
ImageView btn_yes;
Location myLocation;
String address , city , country;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
txt_street = (TextView)findViewById(R.id.txt_coordinates);
txt_city = (TextView)findViewById(R.id.txt_city);
txt_country = (TextView)findViewById(R.id.txt_country);
btn_yes = (ImageView)findViewById(R.id.btn_yes);

setUpIfNeeded();

}

private void setUpIfNeeded() {
if (googleMap == null)
{
try{
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}catch(Exception e){}

if (googleMap != null)
{
setUpMap();
}

}
}

private void setUpMap() {

googleMap.setMyLocationEnabled(true);

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria , true);

myLocation = locationManager.getLastKnownLocation(provider); // Here I get the NULL

googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
double latitude = myLocation.getLatitude();
double longtitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude , longtitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));


try {
convert_adresses(latitude,longtitude);
} catch (IOException e) {
e.printStackTrace();
}

txt_street.setText(address);
txt_city.setText(city);
txt_country.setText(country);

}

public void convert_adresses (double lat , double lng) throws IOException
{
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(lat, lng, 1);

address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
}


Thanks everyone !


0 comments:

Post a Comment