我写了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/