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”?>

<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>

2 . Add the following statements in bold to the MainActivity.java 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; ​
​​​​​​​try
{
​​​​​​​​​​​​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.​*/
​​​​@Override
​​​​public ​void ​onCreate(Bundle ​savedInstanceState)​
{
​​​​​​​​super.onCreate(savedInstanceState); ​​
​​​​​​setContentView(R.layout.main);
​​​​​​​​
//---download an image---
​​​​​​​​Bitmap bitmap = ​​​​​​​​​​​​DownloadImage( ​​​​​​​​​​​​“http://www.streetcar.org/mim/cable/images/cable-01.jpg”); ​
​​​​​​​img = (ImageView) findViewById(R.id.img);
​​​​​​​​img.setImageBitmap(bitmap);
​​​​}
}

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