Glave Glave - 10 months ago 113
Android Question

How to create an AsyncTask properly

I am new to Java and since this question belongs to a very time sensitive project for my work, I dont have the time to learn everything about AsyncTasks.
So my question is:

How do I construct an

out of the following code?

The goal is to draw a route on a map. I fill the
with two
(start-location and the destination of the route). The
is supposed to send those waypoints to a server that sends me back the route.

is the method that finally draws the route on the map.

RoadManager roadManager = new OSRMRoadManager(this);

ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
GeoPoint myLocation = new GeoPoint(51.488978, 6.746994);
Road road = roadManager.getRoad(waypoints);

I guess this has to go in the
-method, right?:

Polyline roadOverlay = RoadManager.buildRoadOverlay(road);

The variable
from the upper code originates from a different method, from which I intend to start the Async task. Meaning, I need to transmit the variable to the AsyncTask when calling it, which I am also not sure how to do exactly.

This is the initialization of the variable

GeoPoint Location = new GeoPoint(Double.parseDouble(place.getLongitude()),

Answer Source

Put the time consuming task in doInBackground(), udpate view in onPostExecute().

public void drawRouteAsync() {
    GeoPoint location = new GeoPoint(Double.parseDouble(place.getLongitude()),
    GeoPoint myLocation = new GeoPoint(51.488978, 6.746994);

    new RouteAsyncTask().execute(location, myLocation);

private class RouteAsyncTask extends AsyncTask<GeoPoint, Void, Road> {
    protected Road doInBackground(GeoPoint... params) {
        ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
        waypoints.add(params[0]); // location
        waypoints.add(params[1]); // myLocation
        RoadManager roadManager = new OSRMRoadManager(mContext); // your context
        Road road = roadManager.getRoad(waypoints); // time consuming
        return road;

    protected void onPostExecute(Road road) {
        Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
        map.getOverlays().add(roadOverlay); // update view