我正在进行网络测验,我遇到了从线程处理活动的问题。这是Client
的代码,它(成功)连接到服务器:
public class Client extends Thread {
private MainActivity activity;
private Socket socket;
private DataInputStream dataIn;
private DataOutputStream dataOut;
private String host;
private int port;
public Client(String host, int port, MainActivity activity) {
this.host = host;
this.port = port;
this.activity = activity;
// At this point of the code, it works just great:
activity.setQuestion("Question", "A", "B", "C", "D", 1);
this.start();
}
private void processMessage( String msg ) {
try {
dataOut.writeUTF(msg);
} catch (IOException e) {
System.out.println(e);
}
}
void handleMessage(String msg) {
if (msg.equals("changeQuestion")) {
// This does not work:
activity.setQuestion("Question", "A", "B", "C", "D", 1);
}
}
@Override
public void run() {
try {
socket = new Socket( host, port );
dataIn = new DataInputStream( socket.getInputStream() );
dataOut = new DataOutputStream( socket.getOutputStream() );
while (true) {
String msg = dataIn.readUTF();
handleMessage(msg);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
在setQuestion(...)
中调用MainActivity
方法,其中问题'和答案按钮的标题设置为字符串。
正如我的评论告诉你的那样,它在线程启动之前确实有效,但是一旦线程启动,它就会崩溃。
这是我的setQuestion(...)
方法,位于MainActivity
:
public void setQuestion(String Q, String A, String B, String C, String D, int correctAnswer) {
TextView tvQuestion = (TextView) findViewById(R.id.tvQuestion);
tvQuestion.setText("");
Button btnA = (Button) findViewById(R.id.btnAnswerA);
Button btnB = (Button) findViewById(R.id.btnAnswerB);
Button btnC = (Button) findViewById(R.id.btnAnswerC);
Button btnD = (Button) findViewById(R.id.btnAnswerD);
tvQuestion.setText(Q);
btnA.setText(A);
btnB.setText(B);
btnC.setText(C);
btnD.setText(D);
this.correctAnswer = correctAnswer;
}
答案 0 :(得分:0)
您的handleMessage()是从新的Thread调用的,而不是主UI线程。考虑将AsyncTask用于此类事情。这是干净的方式。
答案 1 :(得分:0)
无法从线程更新ui。从线程调用setQuestion
,然后在setQuestion中将文本设置为按钮。
检查线程@
下的主题http://developer.android.com/guide/components/processes-and-threads.html
您可以使用Handler
或Asynctask
或runOnUiThread
activity.runOnUiThread(new Runnable() {
public void run() {
activity.setQuestion("Question", "A", "B", "C", "D", 1);
}
}