使用URL中的图像更新ImageView

在我的Android应用程序中,我想要使用从URL指定的图像更新ImageView。 此URL已作为AsyncTask的一部分通过API获取。

我已经定义了ImageView如下:

 

这样,在加载数据时,ProgressDialog后面会出现一个空白图像。

作为AsyncTask的doInBackground的一部分,在获取产品详细信息后,我调用:

 private void createProductScreen(Product product){ Log.i(TAG, "Updating product screen"); //Set the product image ImageView imgView =(ImageView)findViewById(R.id.product_image); Drawable drawable = loadImageFromWeb(product.getImageUrl()); imgView.setImageDrawable(drawable); Log.i(TAG, "Set image"); } 

图像从Web加载如下:

 private Drawable loadImageFromWeb(String url){ Log.i(TAG, "Fetching image"); try{ InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src"); Log.i(TAG, "Created image from stream"); return d; }catch (Exception e) { //TODO handle error Log.i(TAG, "Error fetching image"); System.out.println("Exc="+e); return null; } } 

当它运行时,我在日志中看到“从流创建的图像” ,但是没有看到“设置图像”,并且从不调用AsyncTask的onPostExecute。

有没有人对这个问题有任何想法或更好的方法将图像从空白图像更新到产品图像?

因为您尝试在单独的线程中设置ImageView,所以应该得到一个Exception。 imgView.setImageDrawable(drawable); 必须在同一个UI线程中调用。 由于您使用的是AsyncTask类,因此设置imageview对象的正确位置在onPostExecute方法中。 以doInBackground将Drawable对象返回到onPostExecute方法的方式更改逻辑,然后使用它调用imgView.setImageDrawable(drawable);

将Imageview设置为可绘制图像

 Drawable drawable = loadImageFromWeb(product.getImageUrl()); 

这是问题。

 Drawable drawable = loadImageFromWeb(XXXXUrl); Imageview.setImageDrawable(drawable); 

为drawable提供正确的URL。