私はAndroidプログラミングに不慣れで、Http接続を確立して画像を表示するために作成しているプログラムのヘルプを実際に使用できます。
私はWei-MengLeeによる「BeginningAndroidApplicationDevelopment」の本を使用しています。コードがコンパイルされ、フラグが立てられるエラーはありませんが、プログラムを実行するたびに「エラー接続」メッセージが表示され、画像は表示されません。
GETリクエストのコードのさまざまなサンプルを調べましたが、コードで機能するものが見つかりません。
私はこれまでのところ解決策を見つけるのに苦労しているので、誰もが提供できる助けをいただければ幸いです。
使用許可に関するコードの最後の行は、マニフェストに含まれていました。
ImageView image;
private InputStream OpenHttpConnection(String urlString)
throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if(!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP Connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1) {
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
Bitmap bitmap = DownloadImage("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(bitmap);
}
<uses-permission
android:name="android.permission.INTERNET" />