Mateus Carvalho
Mateus Carvalho

Reputation: 336

Asynctask accessed for two activities

I have a AsyncTask for downloading a route from API Google Directions. The task starts at first Activity, where I show the time and the distance of the user to a point, but my map is in the second activity where I need draw the line of the route. My question is how to maintain a unique download task between two tasks (If the download has not completed in first activity), and access the data of the task on two activities.

public class DownloadDirections {

String urlDownload;
PolylineOptions lineOptions = null;
Context context;
String mTime;
String mDistance;

public DownloadDirections (Context context, String urlDownload){
    this.urlDownload = urlDownload;
    this.context = context;

    new DownloadDirectionsTask().execute(urlDownload);
}

// Fetches data from url passed
private class DownloadDirectionsTask extends AsyncTask<String, Void, String> {

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try {
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);

    }
}


/**
 * A method to download json data from url
 */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

/**
 * A class to parse the Google Places in JSON format
 */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    // Parsing the data in non-ui thread
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try {
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        MarkerOptions markerOptions = new MarkerOptions();
        String distance = "";
        String duration = "";

        if(result != null) {
            if (result.size() < 1) {
                Toast.makeText(context, "No Points", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        if(result != null) {
            // Traversing through all the routes
            for (int i = 0; i < result.size(); i++) {
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);

                // Fetching all the points in i-th route
                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> point = path.get(j);

                    if (j == 0) {    // Get distance from the list
                        distance = (String) point.get("distance");
                        continue;
                    } else if (j == 1) { // Get duration from the list
                        duration = (String) point.get("duration");
                        continue;
                    }

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                }

                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(2);
                lineOptions.color(Color.RED);
                mTime = duration;
                mDistance = distance;

            }

        }

    }
}

}

Upvotes: 0

Views: 64

Answers (1)

cprakashagr
cprakashagr

Reputation: 761

There are lots of options.

  1. Download the entire item in the first activity, pass it to the second as intent data and access in the second activity. You may store the data in the internal storage (Preference, DB or Files depending on the size) if you want, and access accordingly.
  2. You want to execute the task multiple times (one after another): Keep a reference to the task object, and from the second activity call, make a wait call to the first one.
  3. Want to use a service? No prob. Call the service, download the data, store them if very large. If the data is small, pass them via broadcast. Access them in the activity.

Is that what you wanted?

Upvotes: 1

Related Questions