Android - ViewRootImpl$CalledFromWrongThreadException(Android - ViewRootImpl$CalledFromWrongThreadException)
问题描述
我使用 this 来显示来自互联网的图像但它会引发如下错误:
04-12 13:45:05.337: E/AndroidRuntime(27897): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能触摸其视图.
I was using this, to DISPLAY IMAGES FROM THE INTERNET but it throws an error as below:
04-12 13:45:05.337: E/AndroidRuntime(27897): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
public class Order extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new DownloadFilesTask().execute();
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
}
@Override
protected Void doInBackground(Void... params) {
setContentView(R.layout.order);
ImageView imageView = (ImageView)findViewById(R.id.imgView);
imageView.setImageDrawable(createDrawableFromURL("http://savagelook.com/misc/sl_drop2.png"));
return null;
}
}
private Drawable createDrawableFromURL(String urlString) {
Drawable image = null;
try {
URL url = new URL(urlString);
InputStream is = (InputStream)url.getContent();
image = Drawable.createFromStream(is, "src");
} catch (MalformedURLException e) {
image = null;
} catch (IOException e) {
image = null;
}
return image;
}
}
推荐答案
把这个放到onCreate()
ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
imageView = (ImageView)findViewById(R.id.imgView);
new DownloadFilesTask().execute();
}
而你的 AsyncTask
类应该是这样的,
And your AsyncTask
class should be like this,
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
Drawable drawable;
@Override
protected Void doInBackground(Void... params) {
drawable = createDrawableFromURL(
"http://savagelook.com/misc/sl_drop2.png");
return null;
}
protected void onPostExecute(Void result) {
imageView.setImageDrawable(drawable);
}
}
这篇关于Android - ViewRootImpl$CalledFromWrongThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android - ViewRootImpl$CalledFromWrongThreadException
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01