【问题标题】:Printing the output from a Bufferedreader to a TextView将 Bufferedreader 的输出打印到 TextView
【发布时间】:2018-01-16 14:09:12
【问题描述】:

我目前正在编写一个应用程序,它可以作为控制台接收和发送消息到我的套接字服务器。

我想将服务器发送给我的消息输出到文本视图。

我的问题是更改文本视图时出现以下异常

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

我的代码:

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

    }
}

}

据我测试,问题出在这一行:

 message = r.readLine();

因为在此行之前更改 textview 完美,但在此行之后不起作用(它打印“读取行”但在打印“行读取”时遇到错误)

我希望你能帮助我,因为它在互联网上找不到任何东西

亡灵

【问题讨论】:

  • 错误信息看起来很清楚。

标签: java android textview bufferedreader


【解决方案1】:

ThreadActivity 之间实现交互时,您应该使用Handler (info) 或runOnUiThread (info)。

我认为错误抛出在某种程度上被延迟了(由于多线程),所以您在视图实际更改后看到它。可能有另一个线程检查正确的视图操作并在发现验证时抛出此错误(我无法在 Android 文档中找到确切的信息)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多