Android Http Access with HttpUrlConnection to download image – Example

September 7, 2012
By

In this article we will create an Android application which will download an image from a remote HTTP server. The communication between the Android application and the HTTP server will be done using the class HttpUrlConnection.

Once the image is dowloaded completely, it will be displayed in an ImageView widget. Here, the download process will be done in a non-ui thread using an AsyncTask object.

This application is developed in Eclipse (  4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 ) .


1. Create a new Android application project namely “HttpUrlConnectionDownloadImage”

Create a new Android Application Project

Figure 1 : Create a new Android Application Project


2. Design an application launcher icon

Design the launcher icon for this application

Figure 2 : Design the launcher icon for this application


3. Create a blank activity to define MainActivity class

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity class details

Enter MainActivity class Details

Figure 4 : Enter MainActivity class Details


5. Update the file res/values/strings.xml


<resources>

    <string name="app_name">HttpUrlConnectionDownloadImage</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">HttpUrlConnection Demo</string>
    <string name="str_btn_download">Download</string>
    <string name="str_iv_description">Downloaded Image</string>
    <string name="str_tv_url">http://wptrafficanalyzer.in/blog/demo/img6.jpg</string>

</resources>


6. Update the layout of the MainActivity in the file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/et_url"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/str_tv_url"
        android:inputType="textUri"
        tools:context=".MainActivity" />

    <Button
        android:id="@+id/btn_download"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_url"
        android:text="@string/str_btn_download"
        tools:context=".MainActivity" />

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_download"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/str_iv_description"
        tools:context=".MainActivity" />
</RelativeLayout>


7. Update the class MainActivity in the file src/in/wptrafficanalyzer/httpurlconnectiondownloadimage/MainActivity.java


package in.wptrafficanalyzer.httpurlconnectiondownloadimage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Getting a reference to the button
        * in the layout activity_main.xml */
        Button btnDownload = (Button) findViewById(R.id.btn_download);

        /** Defining a click event listener for the button */
        OnClickListener downloadListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(isNetworkAvailable()){
                    /** Getting a reference to Edit text containing url */
                    EditText etUrl = (EditText) findViewById(R.id.et_url);

                    /** Creating a new non-ui thread task */
                    DownloadTask downloadTask = new DownloadTask();

                    /** Starting the task created above */
                    downloadTask.execute(etUrl.getText().toString());
                }else{
                    Toast.makeText(getBaseContext(), "Network is not Available", Toast.LENGTH_SHORT).show();
                }
            }
        };

        /** Setting Click listener for the download button */
        btnDownload.setOnClickListener(downloadListener);
    }

    private boolean isNetworkAvailable(){
        boolean available = false;
        /** Getting the system's connectivity service */
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        /** Getting active network interface  to get the network's status */
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if(networkInfo !=null && networkInfo.isAvailable())
            available = true;

        /** Returning the status of the network */
        return available;
    }

    private Bitmap downloadUrl(String strUrl) throws IOException{
        Bitmap bitmap=null;
        InputStream iStream = null;
        try{
            URL url = new URL(strUrl);
            /** Creating an http connection to communcate with url */
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            /** Connecting to url */
            urlConnection.connect();

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

            /** Creating a bitmap from the stream returned from the url */
            bitmap = BitmapFactory.decodeStream(iStream);

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
        }
        return bitmap;
    }

    private class DownloadTask extends AsyncTask<String, Integer, Bitmap>{
        Bitmap bitmap = null;
        @Override
        protected Bitmap doInBackground(String... url) {
            try{
                bitmap = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            /** Getting a reference to ImageView to display the
            * downloaded image
            */
            ImageView iView = (ImageView) findViewById(R.id.iv_image);

            /** Displaying the downloaded image */
            iView.setImageBitmap(result);

            /** Showing a message, on completion of download process */
            Toast.makeText(getBaseContext(), "Image downloaded successfully", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


8. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.httpurlconnectiondownloadimage"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


9. Displaying the screenshots of the application

Inputting the url of the image to be downloaded

Figure 5 : Inputting the url of the image to be downloaded

 

Image is successfully downloaded

Figure 6 : Image is successfully downloaded


10. Download


11. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , ,

12 Responses to Android Http Access with HttpUrlConnection to download image – Example

  1. Bill Yeh on October 29, 2012 at 9:26 am

    Pretty much the best tutorial I’ve found on the net. Thanks!

  2. devang on November 2, 2012 at 1:56 am

    short but sharp, to the point, nice one buddy, thanx.

  3. Lard on November 9, 2012 at 4:29 pm

    Awesome! Thank you

  4. prateek on December 14, 2012 at 7:25 pm

    awsome one

  5. GauravKumawat on December 18, 2012 at 5:19 pm

    Superbbb!!!

  6. Krunal Panchal on December 25, 2012 at 1:02 am

    just awesome tutorial… but I need a pop blocker which tells me about the data uploaded on a website.
    If anyone can help me then plzz …
    Thanks…

  7. Jai on March 9, 2013 at 5:22 pm

    Great tutorial. Helped alto.

  8. kannan on March 15, 2013 at 10:50 am

    Superbbbb!!!!!!,nice. How to request Android download manager to download multiple files one by one Also I would like to know each and every file download status.
    please help me

  9. Ivan on April 19, 2013 at 7:07 pm

    Congrats for the tutorial!!!
    I would like to do something like that but posting some images into a gridview, maybe I can´t do it in this way becasue are at least 6 images and I should need an imageAdapter for the gridView.
    Any idea??

    Thank you very much

  10. Zee on April 30, 2013 at 5:51 am

    Does this app work on target Android 4.1.1? I created with these specs and got an error message when I tried to run it:
    android:minSdkVersion=”8″
    android:targetSdkVersion=”17″
    Target Android version 4.1.1

    The error message appeared when I ran the app and touch the Download button:
    Unfortunately, httpUrlConnectionDownloadImage has stopped.

  11. Raju on May 16, 2013 at 9:31 am

    very thnx sir…

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner