我有 UI 组件,其中有由 ImageView 组成的表格,现在我想从 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();
}
请告诉我如何实现这一目标?
最佳答案
将 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定义以允许将位图传递给publishProgress方法,如下所示:
AsyncTask<whatever..., Bitmaps, whatever...>()
然后
publishProgress(yourBitmapObject);
protected void onProgressUpdate(Bitmap[] values) {
images[i].setImageBitmap(values[0]);
};
关于java - 安卓 : Updating UI components from async class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511906/