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 AsyncTask
out of the following code?
The goal is to draw a route on a map. I fill the ArrayList
with two Geopoints
(start-location and the destination of the route). The roadManager
is supposed to send those waypoints to a server that sends me back the route.
buildRoadOverlay
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);
waypoints.add(Location);
waypoints.add(myLocation);
Road road = roadManager.getRoad(waypoints);
I guess this has to go in the onPostExecute
-method, right?:
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
map.getOverlays().add(roadOverlay);
The variable location
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 location
:
GeoPoint Location = new GeoPoint(Double.parseDouble(place.getLongitude()),
Double.parseDouble(place.getLatitude()));
Put the time consuming task in doInBackground(), udpate view in onPostExecute().
public void drawRouteAsync() {
GeoPoint location = new GeoPoint(Double.parseDouble(place.getLongitude()),
Double.parseDouble(place.getLatitude()));
GeoPoint myLocation = new GeoPoint(51.488978, 6.746994);
new RouteAsyncTask().execute(location, myLocation);
}
private class RouteAsyncTask extends AsyncTask<GeoPoint, Void, Road> {
@Override
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;
}
@Override
protected void onPostExecute(Road road) {
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
map.getOverlays().add(roadOverlay); // update view
}
}