Undead
Undead

Reputation: 13

Printing the output from a Bufferedreader to a TextView

i am currently programming an app that manly works as a console for receiving and sending messages to my socket server.

I want to output the messages that the server sent me to a textview.

My problem is that i am getting the following exception when changing the textview

W/System.err: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

My code:

public class SocketListener implements Runnable {

public static BufferedReader r;



public void run() {

    try {
        MainActivity.ausgabe.setText("Reading socket");

        String message;
        Boolean run = true;
        while (run) {
            if(r != null) {
                MainActivity.ausgabe.setText("Reading line");
                message = r.readLine();
                MainActivity.ausgabe.setText("Line read");
                if(message != null){
                    MainActivity.ausgabe.setText(message);
                }

            }
        }


    } catch (Exception e) {
        e.printStackTrace();

    }
}

}

As far as i have tested, the problem is in this line:

 message = r.readLine();

because changing the textview before this line works perfekt, but after this line doesnt work (It prints the "reading line" but runs into the error when printing "line read")

I hope you can help me cause i couldnt find anything on the internet

Undead

Upvotes: 0

Views: 220

Answers (1)

Jakub Licznerski
Jakub Licznerski

Reputation: 1088

When implementing interaction between Thread and Activity you should use Handler (info) or runOnUiThread (info).

I think the error throw is somehow delayed (because of multithreading) so you are seeing it after the view has actually changed. Probably there is another thread that checks for correct view manipulation and throws this error when discovers validation (I was unable to find exact info in Android docs).

Upvotes: 1

Related Questions