As I mention in my previous posts, I'm currently developing a simple Android application for news article. In my application, I've used the web services functions like JSON and XML for parsing JSON and XML data from my web server. According Android developer network, we should use AsyncTask while fetching such data format from web servers. Because display "loading" or "processing" message instead of blank screen while fetching data so that our clients won't be confused any more. And it's also good for performance. Likewise, should display "loading image" for our article image while fetching image from web server and to display at device. That's why your device doesn't need to wait to all of images to be loaded.
Here is coding for image AsyncTask.
2import java.lang.ref.WeakReference;
3import java.net.MalformedURLException;
4import java.net.URL;
5
6import android.graphics.Bitmap;
7import android.graphics.BitmapFactory;
8import android.os.AsyncTask;
9import android.widget.ImageView;
10
11public class ImageLoad extends AsyncTask<String, Void, Bitmap> {
12 private String url;
13 private final WeakReference<ImageView> imageViewReference;
14
15 public ImageLoad(ImageView imageView) {
16 imageViewReference = new WeakReference<ImageView>(imageView);
17 }
18
19 protected Bitmap doInBackground(String... params) {
20 url = params[0];
21 try {
22 return BitmapFactory.decodeStream(
23 new URL(url).openConnection()
24 .getInputStream());
25 } catch (MalformedURLException e) {
26 e.printStackTrace();
27 return null;
28 } catch (IOException e) {
29 e.printStackTrace();
30 return null;
31 }
32 }
33
34 protected void onPostExecute(Bitmap result) {
35 if (imageViewReference != null) {
36 ImageView imageView = imageViewReference.get();
37 if (imageView != null) {
38 imageView.setImageBitmap(result);
39 }
40 }
41 }
42
43 protected void onPreExecute() {
44 if (imageViewReference != null) {
45 ImageView imageView = imageViewReference.get();
46 if (imageView != null) {
47 <!---
48 this image will be displayed
49 before being completely loaded from server
50 --->
51 imageView.setImageResource(R.drawable.no_image);
52 }
53 }
54 }
55}
How to use above coding? It's so simple. Check it out following coding.
2
3ImageLoad downloader = new ImageLoad(myicon);
4downloader.execute("http://www.ppshein.net/images/popular.png");
After adding above coding to my application, performance is 50% increased. Hope it's useful and workable.

Above screen, the whilte rectangle box are default images to display before the time actual images from web servers are not completely loaded.

Android
Top of Page