Setting an ImageView with a downloaded image is a fairly common thing to do in Android and there are plenty of tutorials out there for doing just this but I’m going to do something a little different. I’m going to extend an ImageView and have the ImageView take care of the downloading and setting the bitmap.
**Note: remember to set the internet permission in the manifest
When declaring a custom view in xml you need to specify the full package name, see below.
<!--?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"> <com.custom.image.CustomImageView android:id="@+id/image" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout>
Here is the custom ImageView, nothing too complex, all you need is a constructor, an AsyncTask to download the image and a method to start the AsyncTask.
import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.AttributeSet; import android.widget.ImageView; public class CustomImageView extends ImageView { //constructor public CustomImageView(Context context, AttributeSet attrs) { super(context, attrs); } /** * method to start the download * @param url - the url of the image to download */ public void downloadImage(String url){ new GetImage().execute(url); } /** * AsyncTask to download the image in the background * The downloaded bitmap is passed to the onPostExecute and * the ImageView sets the bitmap there (back in the UI thread) * */ private class GetImage extends AsyncTask<String,Void,Bitmap>{ @Override protected Bitmap doInBackground(String... params) { try { return BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap b){ if(b != null) setImageBitmap(b); } } }
And finally the main Activity.
public class CustomImageViewActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //get the custom image view CustomImageView image = (CustomImageView)findViewById(R.id.image); //start the download image.downloadImage("http://cdn.esphoneblog.com/wp-content/uploads/2011/12/android-logo-font.png"); } }
And that is it, a nice clean way to download and set an image.
Leave a comment