java - TextView 类的 setText 方法抛出无法解释的异常

标签 java android exception textview

我写了Android客户端。 ClientThread类实现了Runnable接口(interface),这是run方法:

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 block 包裹该行之前,程序停止了运行。 现在我捕获了异常并且什么也不做。 即使抛出异常,也会设置文本。 那么我怎样才能知道这个异常是什么?

编辑: 正如评论中提到的,通过检查异常对象消息字段:

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();
    }
}

您捕获了异常,但没有对其进行任何处理。打印堆栈跟踪将显示哪一行代码导致引发异常。

关于java - TextView 类的 setText 方法抛出无法解释的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28921441/

相关文章:

java - 为什么@Transactional 在我的代码中不起作用?

exception - GitHub API : create pull-request that already exists should not throw exception

java - AudioSystem.getInputStream(InputStream) 异常

java - 具有Snappy压缩的HBase表中的BulkLoad获取UnsatisfiedLinkError

java - 如何使用 Jackson 和默认类型对 EnumMap 进行(反)序列化?

java - java Swing中是否有像FrameLayout(Android)这样的概念?

java - 在 JPCAP 中等待 ICMP 回显请求消息

android - Firebase 身份验证连接电子邮件与电话

android - 在小部件中使用带有 EditText 的字体

java - 无法将图像插入 Excel 工作表