Monday, June 18, 2012

Downloading an image from the server and displaying it on android screen



This is a sample activity which shows how to get image files from the web and display them using the ImageView view.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a Project downloadImage.
2.) Add the relevant permissions to your AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.sample.downloadImage"

     android:versionCode="1"
     android:versionName="1.0.0">
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" 
       android:label="@string/app_name">
        <activity android:name=".downloadImage"
                 android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
3.) Define a helper function called OpenHttpConnection() in your activity that opens a connection to a HTTP server and returns an InputStream object:
private InputStream OpenHttpConnection(String urlString) throws IOException
{
        InputStream in = null;
        int response = -1;
             
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
               
        if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
     
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();              
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                              
            }                  
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");          
        }
        return in;  
}
4.) Replace main.xml with the following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <ImageView android:id="@+id/img" android:layout_width="wrap_content"
                android:layout_height="wrap_content"android:layout_gravity="center" />
</LinearLayout>
5.) Run the application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. downloadImage. Enter following information:
Project name: downloadImage
Build Target: Google APIs
Application name: downloadImage
Package name: com.sample.downloadImage
Create Activity: downloadImage
On Clicking Finish downloadImage code structure is generated with the necessary Android Packages being imported along with downloadImage.java. downloadImage class will look like following:
package com.sample.downloadImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class downloadImage extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Bitmap bitmap = DownloadImage(
            "http://your/images/url.jpg");
        ImageView img = (ImageView) findViewById(R.id.img);
        img.setImageBitmap(bitmap);
    }

    private InputStream OpenHttpConnection(String urlString)
    throws IOException
    {
        InputStream in = null;
        int response = -1;
             
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
               
        if (!(conn instanceof HttpURLConnection))                  
            throw new IOException("Not an HTTP connection");
     
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();              
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                              
            }                  
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");          
        }
        return in;  
    }
    private Bitmap DownloadImage(String URL)
    {      
        Bitmap bitmap = null;
        InputStream in = null;      
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return bitmap;              
    }
}
Output –The final output:

No comments:

Post a Comment