我正在進行網絡測驗,我遇到了從線程處理活動的問題。這是我對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;
}
您不能更新UI從'thread' – Raghunandan
謝謝。那麼我會找到另一個解決方案。 – user2948462
你可以使用'runOnUiThread'這是一個activity類的方法。檢查我的帖子 – Raghunandan