Android - ViewRootImpl$CalledFromWrongThreadException

2022-09-02 02:45:03

我正在使用这个,以显示来自互联网的图像,但它抛出一个错误,如下所示:
04-12 13:45:05.337:E/AndroidRuntime(27897):由以下原因引起:android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。

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;
        }

}

答案 1

我在尝试使用JNI从c ++更改UI视图时遇到了同样的问题。解决方案是使用

runOnUiThread(new Runnable() {
    public void run(){   
    }
});

runOnUiThread 是一个 Activity 方法,因此我必须使我的活动实例公开为静态,以便能够调用我的公共静态方法,该方法稍后从 JNI 调用。

希望这有助于其他人:)

PS:从这里我学习如何使用JNI http://www.cocos2d-x.org/projects/cocos2d-x/wiki/How_to_use_jni 我以前用cocos2dx制作的Android游戏


答案 2

把这个放进去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

        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);
            }          
        } 

推荐