Home Tutorials Hints & Tips

Getting Started in Android Development

Part 44 - The URLConnection and Testing the AsyncTask

In this tutorial we will set up the URLConnection and also test the AsyncTask by using the URLConnection to download an image file from the Internet. The code for the URLConnection will be placed inside the doInBackground method of the ourAsyncTask subclass set up in the last tutorial.

First of all, we need to add a permission to the Android Manifest to allow Internet access:

<uses-permission android:name="android.permission.INTERNET"/>

We then need to set up an object for the bitmap within the class.

Bitmap bitmap = null;

The modified code for the doInBackground method is shown below:

protected Bitmap doInBackground(String... Url) {
   try {
      bitmap = downloadBitmap(url[0]);
   } catch (IOException e) {
   return bitmap;

"params" has been changed to "url" to reflect better what we are doing in that we are passing a URL to the method. The three dots indicate that the parameters are passed as an array or "varargs" meaning there can be more than one element. There is only one URL so it is identified as url[0]. url[0] is passed into the method that we will define that executes the URLConnection code. We will call this method downloadBitmap. Finally, we need to return the bitmap rather than null.

We can now turn our attention to the downloadBitmap method. We first need to initialize some objects.

Bitmap bitmap = null;
InputStream inputStream = null;
URL url = null;

Within a try and catch, we then need to set the url object to the actual URL of the file to download.

url = new URL(stringUrl);

We then need to create an object of the HttpURLConnection object and inform it of the url.

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

The next line of code establishes the connection:


We then download the file to the input stream and convert the input stream to a bitmap:

inputStream = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);

We can then close the input stream if there are no exceptions:


Finally, we return the bitmap to the doInBackground method.

The AsyncTask and URLconnection are now ready to test. The screenshot below shows the resultant layout with the downloaded image.

Android URL Connection Download

After this tutorial your AsyncTaskActivity.java file should look similar to the one below:

Your Android Manifest file should look similar to the one below:

Download Download tutorial set 3

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved