Within my android application, I'm wanting to update an ImageView, with an image specified from a URL. This URL has been fetched via an API as part of an AsyncTask.
I have defined the ImageView as follows:
<ImageView
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:layout_height="wrap_content"
android:id="@+id/product_image"
android:src="@drawable/no_product_image"
android:layout_marginRight="6dip"
android:layout_width="wrap_content"
/>
That way, whilst the data is loading, there is a blank image present behind a ProgressDialog.
As part o开发者_运维知识库f the doInBackground of the AsyncTask, after fetching the product details, I call:
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");
}
The image is loading from the web as follows:
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;
}
}
When this runs I see "Created image from stream" in the log, but don't see "Set image" and the onPostExecute of the AsyncTask is never called.
Does anyone have any ideas on the issue or a better way of updating the image from the blank image to the product image?
You should get an Exception since you are trying to set the ImageView in a separated thread.
imgView.setImageDrawable(drawable);
must be called in the same UI thread.
Since you are using the AsyncTask class, the right place for set the imageview object is inside the onPostExecute method.
Change you logic in a way that the doInBackground will returns the Drawable object to the onPostExecute method, then use it calling imgView.setImageDrawable(drawable);
Set Imageview to drawable image
Drawable drawable = loadImageFromWeb(product.getImageUrl());
here is problem.
Drawable drawable = loadImageFromWeb(XXXXUrl);
Imageview.setImageDrawable(drawable);
Give a proper URL to drawable.
精彩评论