0

I need a little help with some information/help about LocationManager in Android. I'm using this code to get user's specific information depending on his location,but in some situations I get provider=null (I'm not pretty sure when,because that exception was uploaded to our server and I can't reproduce it).

Here is the sample code :

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria crta = new Criteria(); 
crta.setAccuracy(Criteria.ACCURACY_FINE); 
crta.setAltitudeRequired(false); 
crta.setBearingRequired(false); 
crta.setCostAllowed(true); 
crta.setPowerRequirement(Criteria.POWER_LOW); 
String provider = locationManager.getBestProvider(crta, true);
Log.d("","provider : "+provider);
// String provider = LocationManager.GPS_PROVIDER; 
Location location = locationManager.getLastKnownLocation(provider); 
updateWithNewLocation(location); 
locationManager.requestLocationUpdates(provider, 1000, 0, locationListener);

How can I when my provider is null and if there is a way to get the current location and use it?

Thanks in advance!

Android-Droid
  • 14,365
  • 41
  • 114
  • 185

1 Answers1

1

try this code and dont forget that atleast one of your provider should be enabled

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(true);
crta.setBearingRequired(true);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW); 
String provider = locationManager.getBestProvider(crta, true);
Log.d("","provider : "+provider);
// String provider = LocationManager.GPS_PROVIDER; 
locationManager.requestLocationUpdates(provider, 1000, 0, locationListener);
Location location = locationManager.getLastKnownLocation(provider); 
//updateWithNewLocation(location); 
vipin
  • 2,851
  • 4
  • 18
  • 32
  • i can't see the difference between your code and mine..except that two lines have changed their positions. – Android-Droid Apr 11 '12 at 12:11
  • it was working before too, but the idea is how to prevent provider to be null...because in some situations (i don't know which because I can't reproduce them it's equal to null). – Android-Droid Apr 11 '12 at 12:22
  • at the time where your device dont have location or every provider was disabled you get null – vipin Apr 11 '12 at 12:25
  • in your code you were getting last known location before updaterequest in case you dont have location then it will give null after that start search – vipin Apr 11 '12 at 12:26
  • Bombastic i suggest you one more thing to get location of user try to use with handler or timer so that make your code wait until you will not get location this will give surity of not getting null – vipin Apr 12 '12 at 07:08