class TextView 的 setText 方法抛出无法解释的异常

setText method of class TextView throws unexplained exception

我写了Android客户端。 classClientThread实现了Runnable接口,这是运行方法:

ClientThread.java

 public void run() {
   connect(); //connects the server

   String msg = ""; //holds the msg recieved from server
   try {
      while(connected && (msg = br.readLine())!= null)
      {
         //System.out.println("Server:"+msg);
          if (!msg.isEmpty())
              creatingActivity.displayServerAnswer("Server:"+msg);

         //notify observers//
         this.setChanged();
        //notify+send out recieved msg to Observers
         this.notifyObservers(msg);
      }
   }
   catch(IOException ioe) { }
   finally { disconnect(); connected = false; }
  }

目的是在设备屏幕上显示服务器答案。

MainActivity.java

    public void displayServerAnswer(String answer){
        TextView textView = (TextView)findViewById(R.id.mainTextView);
        try {
            textView.setText(answer);
        }
        catch(Exception e){

    }
}

由于某些原因,当调用 textView.setText(answer); 时抛出异常。我不知道是哪一种。在我用 try-catch 块包裹行之前,程序停止了 运行ning。 现在我抓住了异常,什么也不做。 即使抛出异常也会设置文本。 那么我怎样才能找出这个异常是什么?

编辑: 如评论中所述,通过检查异常对象消息字段:

Only the original thread that created view hirarchy can touch its views

所以现在我明白了异常,但我不明白为什么它只在第二次抛出,客户端线程调用 creatingActivity.displayServerAnswer("Server:"+msg);

  public void displayServerAnswer(String answer){
    TextView textView = (TextView)findViewById(R.id.mainTextView);
    try {
        textView.setText(answer);
    }
    catch(Exception e){
      e.printStackTrace();
    }
}

您正在捕获异常,但未对它执行任何操作。打印堆栈跟踪将显示哪一行代码导致抛出异常。

这是因为您在 运行 方法中从后台线程设置文本。 使用运行onUithread 或处理程序更改text.inside 运行 方法。:)