Can Geocoder Getfromlocation Method Cause A Networkonmainthreadexception To Be Thrown?
I have an app which was tested thoroughly and working fine on Android Gingerbread (and older Android versions). I've noticed from users' reported crash errors that phones running l
Solution 1:
Seems like these Geocoder
methods and any networking or i/o calls are going to throw up a NetworkOnMainThreadException
. So, if in doubt, stick it in a separate thread!
Here's an example of how to call the GeoCoder.getFromLocation()
method from another thread:
newAsyncTask<GeoPoint, Void, Address>()
{
@Overrideprotected Address doInBackground(GeoPoint... geoPoints)
{
try
{
GeocodergeoCoder=newGeocoder(context);
doublelatitude= geoPoints[0].getLatitudeE6() / 1E6;
doublelongitude= geoPoints[0].getLongitudeE6() / 1E6;
List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0)
return addresses.get(0);
}
catch (IOException ex)
{
// log exception or do whatever you want to do with it!
}
returnnull;
}
@OverrideprotectedvoidonPostExecute(Address address)
{
// do whatever you want/need to do with the address found// remember to check first that it's not null
}
}.execute(myGeoPoint);
Post a Comment for "Can Geocoder Getfromlocation Method Cause A Networkonmainthreadexception To Be Thrown?"