简体   繁体   English

为什么我收到异常ViewRootImpl $ CalledFromWrongThreadException?

[英]Why i'm getting exception ViewRootImpl$CalledFromWrongThreadException?

And how should i solve it ? 我应该如何解决呢? This is my button click method that i call it from inside onCreate: 这是我从onCreate内部调用的按钮单击方法:

public void addListenerOnButton()
{
    btnClick = (Button) findViewById(R.id.checkipbutton);
    btnClick.setOnClickListener(new OnClickListener()
    {
        byte[] response = null;
        @Override
        public void onClick(View arg0)
        {
            text = (TextView) findViewById(R.id.textView2);
            Thread t = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    for (int i = 0; i < ipaddresses.length; i++)
                    {
                        try
                        {
                             response = Get(ipaddresses[i]);
                             if (response == null)
                             {
                                  text.setText("Connection Failed: " + generateRunnablePrinter(i));
                             }
                         }
                         catch (Exception e)
                         {
                              String err = e.toString();
                         }
                         if (response != null)
                         {
                             try
                             {
                                 final String a = new String(response, "UTF-8");
                                 text.post(new Runnable()
                                 {
                                     @Override
                                     public void run()
                                     {
                                         text.setText(a);
                                     }
                                 });
                                 iptouse = ipaddresses[i].substring(0, 26);
                                 connectedtoipsuccess = true;
                                 Logger.getLogger("MainActivity(inside thread)").info(a);
                             }
                             catch (UnsupportedEncodingException e)
                             {
                                 e.printStackTrace();
                                 Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
                             }
                             Logger.getLogger("MainActivity(inside thread)").info("test1");
                             break;
                         }
                         else
                         {
                         }
                     }
                }
           });
           t.start();
        }
    });
}

At this place in the method inside the FOR loop the variable 'i' should be final: 在FOR循环内方法的此位置,变量“ i”应为最终变量:

text.setText("Connection Failed: " + generateRunnablePrinter(i));

But since 'i' is also the variable of the FOR loop i can't make it final. 但是由于“ i”也是FOR循环的变量,所以我无法将其定为最终变量。 So i added the method : generateRunnablePrinter 所以我添加了方法:generateRunnablePrinter

private Runnable generateRunnablePrinter(final int value)
{
    return new Runnable() {
        public void run()
        {
            text.setText("Connection Failed: " + ipaddresses[value]);
        }
    };
}

But now using this method I'm getting the exception: 但是现在使用这种方法我得到了例外:

ViewRootImpl$CalledFromWrongThreadException ViewRootImpl $ CalledFromWrongThreadException

You can't change the UI "text of the TextView" from another thread so you can try AsyncTask to do the work in the background in doInBackground() method then change the UI in the method onPostExecute() . 您不能从另一个线程的UI“TextView的文本”改变,所以你可以尝试的AsyncTask做的工作在后台doInBackground()方法,然后更改方法的UI onPostExecute()
Check out the AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html 查看AsyncTask: http : //developer.android.com/reference/android/os/AsyncTask.html

Since you're adjusting your UI, you'll need to run it from the UI thread. 由于您正在调整UI,因此需要从UI线程运行它。 I'd recommend this function: 我建议使用此功能:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
    // Your code here...
    }
});

If you're calling it from anywhere else but an Activity, you'll need to either pass down the activity or get the activity using getActivity() (ie from a fragment), and then call the function from the activity, ie getActivity().runOnUiThread() { ... } 如果要从除Activity之外的其他任何地方调用它,则需要传递该活动或使用getActivity()(即从一个片段中)获取该活动,然后从该活动中调用该函数,即getActivity().runOnUiThread() { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM