How to perform gui operation in doInBackground method?
- by jM2.me
My application reads a user selected file which contains addresses and then displays on mapview when done geocoding. To avoid hanging app the importing and geocoding is done in AsyncTask.
public class LoadOverlayAsync extends AsyncTask<Uri, Integer, StopsOverlay> {
Context context;
MapView mapView;
Drawable drawable;
public LoadOverlayAsync(Context con, MapView mv, Drawable dw)
{
context = con;
mapView = mv;
drawable = dw;
}
protected StopsOverlay doInBackground(Uri... uris)
{
StringBuilder text = new StringBuilder();
StopsOverlay stopsOverlay = new StopsOverlay(drawable, context);
Geocoder geo = new Geocoder(context, Locale.US);
try
{
File file = new File(new URI(uris[0].toString()));
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
StopOverlay stopOverlay = null;
String[] tempLine = line.split("~");
List<Address> results = geo.getFromLocationName(tempLine[4] + " " + tempLine[5] + " " + tempLine[7] + " " + tempLine[8], 10);
if (results.size() > 0)
{
Toast progressToast = Toast.makeText(context, "More than one yo", 1000);
progressToast.show();
}
else if (results.size() == 1)
{
Address addr = results.get(0);
GeoPoint mPoint = new GeoPoint((int)(addr.getLatitude() * 1E6), (int)(addr.getLongitude() * 1E6));
stopOverlay = new StopOverlay(mPoint, tempLine);
}
if (stopOverlay != null)
{
stopsOverlay.addOverlay(stopOverlay);
}
//List<Address> results = geo.getFromLocationName(locationName, maxResults)
}
} catch (URISyntaxException e) {
showErrorToast(e.toString());
//e.printStackTrace();
} catch (FileNotFoundException e) {
showErrorToast(e.toString());
//e.printStackTrace();
} catch (IOException e) {
showErrorToast(e.toString());
//e.printStackTrace();
}
return stopsOverlay;
}
protected void onProgressUpdate(Integer... progress)
{
Toast progressToast = Toast.makeText(context, "Loaded " + progress.toString(), 1000);
progressToast.show();
}
protected void onPostExecute(StopsOverlay so)
{
//mapView.getOverlays().add(so);
Toast progressToast = Toast.makeText(context, "Done geocoding", 1000);
progressToast.show();
}
protected void showErrorToast(String msg)
{
Toast Newtoast = Toast.makeText(context, msg, 10000);
Newtoast.show();
}
}
But if geocode fails, I want a dialog popup to let user edit the address. That would require calling on gui method while in doInBackground. What would be a good workaround this?