Search code examples
javaandroidandroid-studioandroid-asynctaskdownloading-website-files

Do we need to catch the return value of AsyncTask?


I have written an Async task below

   public class DownloadTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            HttpsURLConnection urlConnection = null;
            try {
                URL url = new URL(urls[0]);
                urlConnection = (HttpsURLConnection)url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(inputStream);
                int data = reader.read();
                while (data != -1){
                    char currentData = (char)data;
                    result+=currentData;
                    data = reader.read();
                }
                Log.i("Downloaded data",result);
            }catch (Exception e){
                e.printStackTrace();
            }

            return result;
        }
    }

Here the AsyncTask returns a string value. In the onCreate method I have called the object of this AsyncTask

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        titles = new ArrayList<String>();
        arrayAdapter =new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,titles);
        listView.setAdapter(arrayAdapter);
        //To get json data
        DownloadTask task  = new DownloadTask();
        try {
            task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");
        }catch (Exception e){
            e.printStackTrace();
        }

    }

This code works without an error. But my doubt is don't we need a variable of type string to catch the returned value of AsyncTask. Here no variable is used and it's simply written as task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");. Why doesn't this raise an error. Can anybody please explain. I am new to Android.


Solution

  • The return value of AsyncTask.execute(Params... params) is the task itself as stated in the documentation, so that you can keep a reference of it. If you just ignore the return value, this does not result in an error.

    An AsyncTask works asynchronously. That's why you retrieve the result later in the onPostExecute(Result result) method of the AsyncTask. This method is run on the UI thread, so you can update views, etc. there.