Day_Dreamer Day_Dreamer - 2 years ago 79
Android Question

setText method of class TextView throws unexplained exception

I wrote Android client.
The class ClientThread implements Runnable interface, this is the run method:

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


The purpose was to display the server answer on the device screen.

MainActivity.java

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

}
}


From some reason when
textView.setText(answer);
is called an exception is thrown. I don't know of which kind. before I wrapped the line with try-catch block the program stopped the running.
Now I catch the exception and do nothing. Even the exception is thrown the text is set.
So how can I find out what is this exception?

EDIT:
As was mentioned in the comments, by checking the exception object message field:


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


So now I understand the exception but I don't understand why it was thrown only in the second time, the client thread called
creatingActivity.displayServerAnswer("Server:"+msg);

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

You are catching the exception but not diong anything with it. Printing a stack trace will show you which line of code caused the exception to be thrown.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download