![](/img/trans.png)
[英]Timer causing ViewRootImpl$CalledFromWrongThreadException?
[英]Why i'm getting exception ViewRootImpl$CalledFromWrongThreadException?
我应该如何解决呢? 这是我从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();
}
});
}
在FOR循环内方法的此位置,变量“ i”应为最终变量:
text.setText("Connection Failed: " + generateRunnablePrinter(i));
但是由于“ i”也是FOR循环的变量,所以我无法将其定为最终变量。 所以我添加了方法:generateRunnablePrinter
private Runnable generateRunnablePrinter(final int value)
{
return new Runnable() {
public void run()
{
text.setText("Connection Failed: " + ipaddresses[value]);
}
};
}
但是现在使用这种方法我得到了例外:
ViewRootImpl $ CalledFromWrongThreadException
您不能从另一个线程的UI“TextView的文本”改变,所以你可以尝试的AsyncTask做的工作在后台doInBackground()
方法,然后更改方法的UI onPostExecute()
查看AsyncTask: http : //developer.android.com/reference/android/os/AsyncTask.html
由于您正在调整UI,因此需要从UI线程运行它。 我建议使用此功能:
runOnUiThread(new Runnable() {
@Override
public void run() {
// Your code here...
}
});
如果要从除Activity之外的其他任何地方调用它,则需要传递该活动或使用getActivity()(即从一个片段中)获取该活动,然后从该活动中调用该函数,即getActivity().runOnUiThread() { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.