2013-11-02 89 views
1

我正在進行網絡測驗,我遇到了從線程處理活動的問題。這是我對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

您不能更新UI從'thread' – Raghunandan

+0

謝謝。那麼我會找到另一個解決方案。 – user2948462

+0

你可以使用'runOnUiThread'這是一個activity類的方法。檢查我的帖子 – Raghunandan

回答

0

你的handleMessage()正在從新線程調用,而不是在主UI線程。考慮使用AsyncTask來完成此類事情。這是乾淨的方式。

+0

我知道。然而,我認爲,我可以從線程內更新UI,這似乎是非法的。不過謝謝你。 – user2948462

+0

是的,不要這樣做 - 如果它似乎有效,它可能每隔一段時間就會出現一次故障 –