Creating Bitmaps from the internet via Apache HttpClient

Last week I blogged about the Android DownloadManager. As a result I received the question how to create a bitmap from internet ressources the “normal” way. ;-)

Here is a small example which uses the Apache HttpClient in Android to download a png file and create a bitmap from it. This bitmap will then be assigned to a ImageView.

Here is the layout file “main.xml”.

<?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">
	<Button android:text="Click to start download" android:onClick="downloadPicture"
		android:layout_height="wrap_content" android:layout_width="wrap_content" />
	<ImageView android:src="@drawable/icon" android:id="@+id/imageView1"
		android:layout_height="match_parent" android:layout_width="match_parent"></ImageView>
</LinearLayout>


package de.vogella.android.bitmap.httpdownload.simple;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class DownloadExampleActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

	}

	public void downloadPicture(View view) {
		final ProgressDialog dialog = ProgressDialog.show(this, "Download",
				"downloading");
		dialog.show();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					final Bitmap downloadBitmap = downloadBitmap("http://www.vogella.de/img/lars/LarsVogelArticle7.png");
					final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							imageView.setImageBitmap(downloadBitmap);
						}
					});

				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					dialog.dismiss();
				}
			}
		}).start();

	}

	private Bitmap downloadBitmap(String url) throws IOException {
		HttpUriRequest request = new HttpGet(url.toString());
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(request);

		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		if (statusCode == 200) {
			HttpEntity entity = response.getEntity();
			byte[] bytes = EntityUtils.toByteArray(entity);

			Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
					bytes.length);
			return bitmap;
		} else {
			throw new IOException("Download failed, HTTP response code "
					+ statusCode + " - " + statusLine.getReasonPhrase());
		}
	}
}

Also add the permission to use the internet to your app.

Hope this helps. A introduction to Networking with Android can be found here.

You find me also on Twitter.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Android and tagged , . Bookmark the permalink.

4 Responses to Creating Bitmaps from the internet via Apache HttpClient

  1. dpimka says:

    Nice!

    Interesting what are the pro/cons of this compared to using java.net.HttpURLConnection?

  2. Lars Vogel says:

    @dpimka java.net.HttpURLConnection on Android uses Apache HttpClient under the hood.

  3. Byte Bender says:

    Thanks so much for this example. I will be using this for one of the apps I am working on tomorrow!

  4. cronaldoyang says:

    very nice.

Comments are closed.