1 import java.io.IOException;
2 import java.io.InputStream;
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import org.apache.http.HttpResponse;
7 import org.apache.http.client.ClientProtocolException;
8 import org.apache.http.client.methods.HttpGet;
9 import org.apache.http.impl.client.DefaultHttpClient;
10
11 import android.graphics.drawable.Drawable;
12 import android.os.Handler;
13 import android.os.Message;
14 import android.widget.ImageView;
15
16 public class DrawableManager {
17
18 private final Map<String, Drawable> drawableMap;
19
20 public DrawableManager() {
21 drawableMap = new HashMap<String, Drawable>();
22 }
23
24 public Drawable fatchDrawable(String urlString) {
25 if (drawableMap.containsKey(urlString)) {
26 return drawableMap.get(urlString);
27 }
28 try {
29 InputStream is = fetch(urlString);
30 Drawable drawable = Drawable.createFromStream(is, "src");
31 drawableMap.put(urlString, drawable);
32 return drawable;
33 } catch (ClientProtocolException e) {
34 // TODO Auto-generated catch block
35 e.printStackTrace();
36 return null;
37 } catch (IOException e) {
38 // TODO Auto-generated catch block
39 e.printStackTrace();
40 return null;
41 }
42
43 }
44
45 public void fetchDrawableOnThread(final String urlString,
46 final ImageView imageView) {
47 if (drawableMap.containsKey(urlString)) {
48 imageView.setImageDrawable(drawableMap.get(urlString));
49 }
50 final Handler handler = new Handler() {
51
52 @Override
53 public void handleMessage(Message msg) {
54 // TODO Auto-generated method stub
55 imageView.setImageDrawable((Drawable) msg.obj);
56 }
57 };
58
59 Thread thread = new Thread() {
60
61 @Override
62 public void run() {
63 // TODO Auto-generated method stub
64 Drawable drawable = fatchDrawable(urlString);
65 Message msg = handler.obtainMessage(1, drawable);
66 handler.sendMessage(msg);
67 }
68 };
69 thread.start();
70 }
71
72 private InputStream fetch(String urlString) throws ClientProtocolException,
73 IOException {
74 DefaultHttpClient httpClient = new DefaultHttpClient();
75 HttpGet request = new HttpGet(urlString);
76 HttpResponse response = httpClient.execute(request);
77 return response.getEntity().getContent();
78
79 }
80 }