我有UI组件,其中包含由ImageViews组成的表,现在我想从URL设置图像。
现在当我尝试异步调用将图像设置为UI的另一个类时,它给出了一个错误,即UI只能由UI线程更新。我想加载UI并在图像可用时加载它们。
这是我的代码:
Calling function...
new AsyncImageLoader(context,imgviewArray).execute();
// Called class..
@Override
protected Void doInBackground(Void... urls) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
int i = 0;
try{
db=new MyDB(mainact_instance);
System.out.println("Inside doInBackground");
if(isNetworkAvailable())
{
System.out.println("Network connected");
System.out.println("Fetching from network-Images");
Movie[] movies = db.selectRecords();
for(Movie mv : movies)
{
try {
URL url = new URL(IMAGE_URL+mv.getId()+".jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
images[i].setImageBitmap(bmp);
i++;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else{
System.out.println("Network not connected..fetching max id row");
}
}catch(Exception ex){ex.printStackTrace();
}
return null;
//db.close();
}
请告诉我如何实现这一目标?
答案 0 :(得分:3)
将与您的UI线程相关的代码移至onPostExecute
|| onProgressUpdate
例如:
protected void onPostExecute(Long result) {
// after finishing fetching your image from URL, update the ImageView here
images[i].setImageBitmap(bmp);
}
我可以看到您正在AsyncTask
内下载多个图像,然后您可以使用PublishProgress
更新AsyncTask定义以允许将Bitmaps传递给publishProgress方法,如下所示:
AsyncTask<whatever..., Bitmaps, whatever...>()
然后
publishProgress(yourBitmapObject);
protected void onProgressUpdate(Bitmap[] values) {
images[i].setImageBitmap(values[0]);
};