1

I'm using AsyncTask and all the examples I found about an AsyncTask is inside an activity.

I'm trying to make an application with a lot of activity and some must download a HTML page. I don't really want to copy-paste the same code all the time in every activity. I find this to be dirty.

So I need to do it as a special class Async HttpGet and pass the function with an argument. I will execute after the doinbackground (different for every activity).

Is this possible or do I need to copy-paste my code in every activity and change the do in background to do what I need after downloading the HTML page?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jebik
  • 778
  • 2
  • 8
  • 26
  • 1
    I've just answered a [similar question here](http://stackoverflow.com/questions/16477091/use-the-same-asynctask-to-update-different-views/16477195#16477195) and I guess this question was asked many times before. – Thibault D. May 10 '13 at 08:39
  • @Jebik, You can try this: http://stackoverflow.com/questions/10768449/android-can-i-put-asynctask-in-a-separate-class-and-have-a-callback – GVillani82 May 10 '13 at 08:39
  • I read and this and apparently this work by the sa,e way for my probleme i will try thank – Jebik May 10 '13 at 08:43
  • check this [answer](http://stackoverflow.com/a/16400981/1329126) – Sankar V May 10 '13 at 08:50

3 Answers3

3

Just create a class that extends AsyncTask that you can reuse.

public abstract class MyAsyncTask extends AsyncTask<Void, Void, String> {

    private final String url;

    public MyAsyncTask(String url){
        this.url = url;
    }

    @Override
    protected String doInBackground(Void... params){
        // get data from url.
        return null;
    }

}

And then to call it, just create an instance of that class.

new MyAsyncTask("http://www.google.com"){
    public void onPostExecute(String result){
        // update your views.
    }
}.execute();
alex
  • 6,359
  • 1
  • 23
  • 21
3

Here's an AsyncTask that will download data from a url and update the calling activity.

Make sure your calling activity implements the interface DownloadDataTask.DownloadCompleteHandler and that it passes itself as parameter to the DownloadDataTask constructor.

public class DownloadDataTask extends AsyncTask<String, Integer, String> {

    public interface DownloadCompleteHandler
    {
        public void handleDownloadComplete(String result);
    }

    private DownloadCompleteHandler handler;
    private String url;

    public DownloadDataTask(DownloadCompleteHandler handler, String url) {
        this.handler = handler;
        this.url = url;
    }


    /* AsyncTask methods */

    @Override
    protected String[] doInBackground(String... empty) {
        return downloadData(url);
    }

    @Override
    protected void onPostExecute(String result) {
        handler.handleDownloadComplete(result);
    }

    /* Downloading Data */

    private String downloadData(String urlStr) {
        InputStream is = null;
        String result = new String();

        try {
            is = getInputStream(urlStr);

            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result += inputLine;            
        } catch (MalformedURLException ex) {
            return "Malformed URL: " + ex.getMessage();
        } catch (SocketTimeoutException ex) {
            return "Connection timed out";
        } catch (IOException ex) {
            return "IOException: " + ex.getMessage();
        }

        finally {
            if (is != null)
                is.close();
        }

        return result;      
    }

    private InputStream getInputStream(String urlStr) throws IOException 
    {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setReadTimeout(7000);
        conn.setConnectTimeout(7000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);

        conn.connect();
        return conn.getInputStream();
    }   
}
tbkn23
  • 5,205
  • 8
  • 26
  • 46
2

Well what you can do is create an listener for AsyncTask completion, which listens when your AsyncTask is completed and return you the data. I had created an example to execute database queries in background thread and then returning the data to the Activity. Just check it and you can create similar AsyncTask for your problem.

UPDATE:-

  • Also you can use BroadCastReceiver as a Listener when your AsyncTask is completed and return the value.
  • Interface is another option for creating a Listener for AsyncTask. Here is a demo from my github
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242