AndroidでURLの画像を読み込んでDrawableに表示する方法のメモ
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.openConnection().getInputStream();
return content;
}
public Drawable createDrawable(String uri)
{
try {
InputStream is = (InputStream) fetch(uri);
Drawable img = Drawable.createFromStream(is, "");
is.close();
return img
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e("createDrawable","error:"+uri);
return null;
} catch (IOException e) {
e.printStackTrace();
Log.e("createDrawable","error:"+uri);
return null;
}
}
通常はurl.openStream()
を使うが、回線が細いスマートフォンで実行した場合、タイムアウトが発生してしまうことがある。
そういう場合url.openConnection().getInputStream();
を使うことでタイムアウトを任意に決めることができる。
タイムアウト時間を設定するにはurl.openConnection().setConnectTimeout(XXX)
を使うらしい
http://stackoverflow.com/questions/3906372/java-openstream-error