質問編集履歴
1
ソースコードの追加
test
CHANGED
File without changes
|
test
CHANGED
@@ -3,3 +3,129 @@
|
|
3
3
|
本に書いてあるプログラムを見ながら勉強しているのですが、AsyncTaskのdoInBackgroundメソッド内でgetTag();を使っているのでその通りに記述してみると、Method getTag must be called from the UI threadという警告が出ます。
|
4
4
|
|
5
5
|
UIスレッドでしか使えないよ、というような警告であると解釈したのですが、本の内容が間違っているのでしょうか。それとも何か別に原因があるのでしょうか。
|
6
|
+
|
7
|
+
|
8
|
+
|
9
|
+
ImageLoaderTask.java
|
10
|
+
|
11
|
+
Webから画像の読み込みを行うクラスです。
|
12
|
+
|
13
|
+
|
14
|
+
|
15
|
+
import android.content.Context;
|
16
|
+
|
17
|
+
import android.graphics.Bitmap;
|
18
|
+
|
19
|
+
import android.graphics.BitmapFactory;
|
20
|
+
|
21
|
+
import android.net.http.AndroidHttpClient;
|
22
|
+
|
23
|
+
import android.os.AsyncTask;
|
24
|
+
|
25
|
+
import android.widget.ImageView;
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
import org.apache.http.HttpResponse;
|
30
|
+
|
31
|
+
import org.apache.http.client.methods.HttpGet;
|
32
|
+
|
33
|
+
|
34
|
+
|
35
|
+
import java.io.IOException;
|
36
|
+
|
37
|
+
|
38
|
+
|
39
|
+
public class ImageLoaderTask extends AsyncTask<ImageView, Void, Bitmap> {
|
40
|
+
|
41
|
+
private static final String USER_AGENT = "WeatherForecasts Sample";
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
private final Context context;
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
Exception exception;
|
50
|
+
|
51
|
+
ImageView imageView;
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
public ImageLoaderTask(Context context) {
|
56
|
+
|
57
|
+
this.context = context;
|
58
|
+
|
59
|
+
}
|
60
|
+
|
61
|
+
|
62
|
+
|
63
|
+
@Override
|
64
|
+
|
65
|
+
protected Bitmap doInBackground(ImageView... params) {
|
66
|
+
|
67
|
+
imageView = params[0];
|
68
|
+
|
69
|
+
String url = (String) imageView.getTag(); /*ここに警告が出る*/
|
70
|
+
|
71
|
+
try {
|
72
|
+
|
73
|
+
return getImage(context, url);
|
74
|
+
|
75
|
+
} catch (IOException e) {
|
76
|
+
|
77
|
+
exception = e;
|
78
|
+
|
79
|
+
}
|
80
|
+
|
81
|
+
return null;
|
82
|
+
|
83
|
+
}
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
@Override
|
88
|
+
|
89
|
+
protected void onPostExecute(Bitmap bitmap) {
|
90
|
+
|
91
|
+
super.onPostExecute(bitmap);
|
92
|
+
|
93
|
+
|
94
|
+
|
95
|
+
if (bitmap != null) {
|
96
|
+
|
97
|
+
imageView.setImageBitmap(bitmap);
|
98
|
+
|
99
|
+
}
|
100
|
+
|
101
|
+
}
|
102
|
+
|
103
|
+
|
104
|
+
|
105
|
+
private static Bitmap getImage(Context context, String url) throws IOException {
|
106
|
+
|
107
|
+
AndroidHttpClient client = AndroidHttpClient.newInstance(USER_AGENT, context);
|
108
|
+
|
109
|
+
|
110
|
+
|
111
|
+
HttpGet get = new HttpGet(url);
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
try {
|
116
|
+
|
117
|
+
HttpResponse response = client.execute(get);
|
118
|
+
|
119
|
+
|
120
|
+
|
121
|
+
return BitmapFactory.decodeStream(response.getEntity().getContent());
|
122
|
+
|
123
|
+
} finally {
|
124
|
+
|
125
|
+
client.close();
|
126
|
+
|
127
|
+
}
|
128
|
+
|
129
|
+
}
|
130
|
+
|
131
|
+
}
|