gpt4 book ai didi

java - 处理线程中的 Activity

转载 作者:行者123 更新时间:2023-12-01 04:12:52 24 4
gpt4 key购买 nike

我正在做一个网络测验,并且遇到了处理线程 Activity 的问题。这是我的 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。 setQuestion 从线程中调用,您可以在 setQuestion 中将文本设置为按钮。

检查主题@下的主题

http://developer.android.com/guide/components/processes-and-threads.html

您可以使用HandlerAsynctaskrunOnUiThread

activity.runOnUiThread(new Runnable() {
public void run() {
activity.setQuestion("Question", "A", "B", "C", "D", 1);
}
}

关于java - 处理线程中的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com