问题
What I need it to have it once the app stops reciving text from the server saying that it is now disconected I need to set the button to say that it is disconnected, this is what I have right now (this is in a while loop I just didnt post all of the code)
Thread.sleep(10);
counter++;
if (counter >= 100)
{
Log.d("ClientActivity","send S");
counter = 0;
out.println("S");
A2MCString = in.readLine();
Log.d("ClientActivity","got " + A2MCString);
if (A2MCString == null)
{
connected = false;
Log.d("ClientActivity","Closed1");
Connect.setText("Connect");
Log.d("ClientActivity","Closed2");
Connect.setBackgroundResource(R.drawable.contect_button);
Log.d("ClientActivity","Closed3");
DeBug.setText("Disconnected from " + serverIpAddress);
Log.d("ClientActivity","Closed4");
}
the app crashes when I try to set connect to "Connect" the logCat error is "android.view.ViewRoot$CalledFromWrongThreadException" If you could help me it would be great!
回答1:
Use runOnUiThread or a handler to make changes to UI from a thread.. I think this line is causing the error..
Connect.setBackgroundResource(R.drawable.contect_button);
put it in runOnUiThread in your thread like this
runOnUiThread(new Runnable() {
public void run() {
Connect.setBackgroundResource(R.drawable.contect_button);
}
});
来源:https://stackoverflow.com/questions/10374519/can-you-set-textview-text-within-a-thread