Sunday, August 11, 2013

Load Bitmap from internet in background thread using AsyncTask

This exercise show how to load bitmap from internet.

Load Bitmap from internet in background thread using AsyncTask


To load bitmap from internet, we can call the method:
BitmapFactory.decodeStream(networkUrl.openConnection().getInputStream());

BUT we have to do it in background thread other than Main Thread (Refer to the post android.os.NetworkOnMainThreadException). That's why we implement AsyncTask here.

Main Code:
package com.example.androidcolor;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class MainActivity extends Activity {

ImageView targetImage;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
targetImage = (ImageView)findViewById(R.id.target);

//Load bitmap from internet
String onLineImage = "http://goo.gl/1VArP";
URL onLineURL;

try {
onLineURL = new URL(onLineImage);
new MyNetworkTask(targetImage).execute(onLineURL);
} catch (MalformedURLException e) {
e.printStackTrace();
}

}

private class MyNetworkTask extends AsyncTask<URL, Void, Bitmap>{

ImageView tIV;

public MyNetworkTask(ImageView iv){
tIV = iv;
}

@Override
protected Bitmap doInBackground(URL... urls) {

Bitmap networkBitmap = null;

URL networkUrl = urls[0]; //Load the first element
try {
networkBitmap = BitmapFactory.decodeStream(
networkUrl.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}

return networkBitmap;
}

@Override
protected void onPostExecute(Bitmap result) {
tIV.setImageBitmap(result);
}

}

}


layout:
<LinearLayout 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"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<ImageView
android:id="@+id/target"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>


Remark: Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.

download filesDownload the files.