2011-05-03 86 views
1

我有一个ImageView,我需要做的就是在应用程序加载时从intetrnet中显示图像。有没有一个非常简单的方法来做到这一点?Android - 如何显示来自URL的图像?

+2

可能重复的[如何在Android中显示互联网图像??](http://stackoverflow.com/questions/4223472/how从Android的互联网到显示图像) – Aleadam 2011-05-03 16:00:47

回答

0
HttpClient client = new DefaultHttpClient(); 
HttpGet get = new HttpGet(url); 

HttpResponse response = client.execute(get); 
Bitmap bitmap = BitmapFactory.decodeStream(response.getEntity().getContent()); 
+0

client.execute(get);立即得到下划线,并且错误显示“未处理的异常类型ClientProtocolException” – 2011-05-03 16:37:06

+0

因此,处理异常类型...将它围绕在try/catch中 – 2011-05-03 16:41:51

+0

做了那个。 FC和崩溃。为什么我应该得到那个错误? – 2011-05-03 16:42:25

4

ImageView.setImageURI似乎不适用于互联网资源,所以您应该自己阅读位图。

InputStream is = new URL("http://example.com/myimage.jpg").openStream(); 
Bitmap bitmap = BitmapFactory.decodeStream(is); 
is.close(); 
ImageView iv = (ImageView) findViewById(R.id.myImage); 
iv.setImageBitmap(bitmap); 

但是这会在UI线程上加载图像,这可能会导致打嗝。最好是在不同的线程,例如使用:

new AsyncTask<String, Void, Bitmap>() { 
    protected Bitmap doInBackground(String... params) { 
     try { 
      return loadBitmap(params[0]); 
     } catch (Exception e) { 
      Log.e("imagetask", "error loading bitmap", e); 
      return null; 
     } 
    } 

    protected Bitmap loadBitmap(String urlSpec) throws IOException { 
     InputStream is = new URL(urlSpec).openStream(); 
     try { 
      return BitmapFactory.decodeStream(is); 
     } finally { 
      is.close(); 
     } 
    } 

    protected void onPostExecute(Bitmap bitmap) { 
     if (bitmap != null) { 
      ImageView iv = (ImageView) findViewById(R.id.myImage); 
      iv.setImageBitmap(bitmap); 
     } 
    } 
}.execute("http://example.com/myimage.jpg"); 
+0

我有这个代码运行没有错误,但图像从不显示。 imageview是空的。有什么想法吗? – 2011-05-03 16:54:11

+0

@JJD,不是真的......有没有在LogCat中引起异常和/或可见的异常?我将为异常处理添加一些代码,我把它留下了。 – beetstra 2011-05-03 17:04:21

+0

我需要在清单中添加Internet权限。谢谢! – 2011-05-03 17:10:39