Friday, 20 March 2015

Android Download Image from URL.

Downloading Binary data 


One of the common tasks you need to perform is downloading binary data from the Web. For example, you may want to download an image from a server so that you can display it in your application.
The following Example shows how this is done.
1 .Add the following statements in bold to the main.xml file: 

<?xml ​version=”1.0”​encoding=”utf-8”?>

​​​​android:layout_width=”fill_parent” ​​
​​android:layout_height=”fill_parent” ​​​​>

<ImageView ​​​​android:id=”@+id/img” ​
​​​​android:layout_height=”wrap_content” ​
​​​android:layout_gravity=”center” />


2 . Add the following statements in bold to the file: 

public ​class ​MainActivity​ extends​ Activity​
​​​​ImageView img;
private​ InputStream ​OpenHttpConnection(String ​urlString) ​​​​throws​IOException
private Bitmap DownloadImage(String URL) ​​​​
​​​​​​​​Bitmap bitmap = null;
​​​​​​​​InputStream in = null; ​
​​​​​​​​​​​​in = OpenHttpConnection(URL);
​​​​​​​​​​​​bitmap = BitmapFactory.decodeStream(in);
​​​​​​​​​​​​in.close(); ​​​​​​​​
catch (IOException e1)
​​​​​​​​​​​​Toast.makeText(this, e1.getLocalizedMessage(), ​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show();
​​​​​​​​​​​​e1.printStackTrace(); ​​​​​​​​
​​​​​​​​return bitmap;
/**​Called​ when ​the ​activity ​is ​first ​created.​*/
​​​​public ​void ​onCreate(Bundle ​savedInstanceState)​
​​​​​​​​super.onCreate(savedInstanceState); ​​
//---download an image---
​​​​​​​​Bitmap bitmap = ​​​​​​​​​​​​DownloadImage( ​​​​​​​​​​​​“”); ​
​​​​​​​img = (ImageView) findViewById(;

How It Works 

The DownloadImage() method takes the URL of the image to download and then opens the connection to the server using the OpenHttpConnection() method that you have defined earlier. Using the InputStream object returned by the connection, the decodeStream() method from the BitmapFactory class is used to download and decode the data into a Bitmap object. The DownloadImage() method returns a Bitmap object.

* The image is then displayed using an ImageView view.

No comments:

Post a Comment