Android - ViewRootImpl$CalledFromWrongThreadException

前端 未结 4 1251
有刺的猬
有刺的猬 2020-11-30 12:28

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.View

相关标签:
4条回答
  • 2020-11-30 12:39

    If you would like to do this job in fragment, you should call UI thread from activity in fragment.

    getActivity().runOnUiThread(new Runnable() {
      public void run(){
    
        ... //your job 
    
      }
    });
    

    @canerkaseler

    0 讨论(0)
  • 2020-11-30 12:48

    I think this line is causing the error..

      imageView.setImageDrawable(createDrawableFromURL("http://savagelook.com/misc/sl_drop2.png"));
    

    and the error explains why it is so..

         Only the original thread that created a view hierarchy can touch its views.
    

    this error is caused because you are trying to change the User Interface on mainthread from some other thread.. here doInBackground in your case...

    0 讨论(0)
  • 2020-11-30 12:49

    I got the same problem trying to change UI view from c++ using JNI. The solution was use

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

    runOnUiThread is an Activity method so I have to make my activity instance public static to be able to call on my public static method who later call from JNI.

    Hope this help others :)

    PS: from here I learn how to use JNI http://www.cocos2d-x.org/projects/cocos2d-x/wiki/How_to_use_jni for my android game previously made with cocos2dx

    0 讨论(0)
  • 2020-11-30 12:50

    Put this in 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();       
        } 
    

    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);
                }          
            } 
    
    0 讨论(0)
提交回复
热议问题