0

我正在尝试检索服务器上的图片。所以我试图用以下方法检索它:

  static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) { 
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent(); 
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();  
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        // Could provide a more explicit error message for IOException or IllegalStateException
        getRequest.abort();
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

然后在另一种方法中,我有以下两行:

      ImageView e = (ImageView) findViewById(R.id.img);
      e.setImageBitmap(downloadBitmap(img_url(param1.img)));

和 xml

      <?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <!-- Name Label -->
    <ImageView
      android:id="@+id/img"  
      android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:contentDescription="@string/picture">         
    </ImageView>

但是图片没有显示,我没有收到任何错误。谁能告诉我我做错了什么?

4

2 回答 2

0

我建议使用“通用图像加载器”库来显示图像。

于 2012-10-06T19:33:43.563 回答
0

我将首先在这个 catch 语句中添加一个日志语句:

} catch (Exception e) {
    // Could provide a more explicit error message for IOException or IllegalStateException
    getRequest.abort();
} 

它可能会在其中引发另一个您不知道的异常。

于 2012-10-06T21:39:38.913 回答