Tuesday, September 28, 2010

How to download and display Images in android

In this article, let's turn our attention to some bread-and-butter issues—like connecting your Android application to the Web to download files.
Very often, you need to connect your Android application to the outside world, such as downloading images as well as consuming web services. This article will show you how to make your Android application communicate with the outside world using an HTTP connection.


public class main extends Activity {
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Bitmap bitmap =
            DownloadImage(
            "http://ichart.finance.yahoo.com/instrument/1.0/%5ENSEI/chart;range=1d/image;size=239x110");
        ImageView img = (ImageView) findViewById(R.id.ImageView01);
        img.setImageBitmap(bitmap);
    }
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;              
    }
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;    
    }
}


Please add permission to access internet in androidmanifest.xml file..
<uses-permission android:name="android.permission.INTERNET"></uses-permission>.




I hope you found this article helpful...

Your Ad Here