Wednesday, 21 November 2012

Loading a image from server to your ImageView

  Note:-Add this line in your manifest.xml file           <uses-permission android:name="android.permission.INTERNET"/>
   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" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
          />

</RelativeLayout>


 ImageFromServer.java


 
    package com.dci.imagefromserver;

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 ImageFromServer extends Activity {
   
       @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Bitmap bitmap = DownloadImage(
        "http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
    ImageView img = (ImageView) findViewById(R.id.image);
    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


No comments:

Post a Comment