2 znl 12 znl_12 于 2013.09.23 16:13 提问

客户端服务器请求程序时的线程错误

我想给daytime创建一个客户端请求程序,例如客户写入一个服务器地址,服务器响应,客户端的写入返回。但是获取的是:"Only the original thread that created a view hierarchy can touch its views." 我在按钮的监听器事件中创建了一个新的线程。
代码如下:

static Socket socket;
TextView result;
EditText server;
Button connect;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    result = (TextView)findViewById(R.id.result);
    server =(EditText)findViewById(R.id.serverField);
    result.setMovementMethod(new ScrollingMovementMethod());
    connect = (Button)this.findViewById(R.id.enter);
    connect.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new Thread(new Runnable(){
                public void run(){
                    socket = null;
                    String timestamp;
                    try{
                        socket = new Socket(server.getText().toString(), Server_Port);
                        InputStream input = socket.getInputStream();
                        BufferedReader socket_input = new BufferedReader(new InputStreamReader(input));
                        result.setText(result.getText()+"Connected to: "+socket.getInetAddress()+" on port "+socket.getPort());
                        while(true){
                            timestamp = socket_input.readLine();
                            if(timestamp == null){
                                result.setText(result.getText()+"\n"+"Server closed connection");
                                break;
                            }
                            result.setText(result.getText()+"\nDaytime: "+timestamp);
                        }
                    }
                    catch(IOException error){
                        result.setText(""+error);
                    }
                    finally{
                        try{
                            if(socket != null){
                                socket.close();
                            }
                        }
                        catch(IOException error){
                            result.setText(""+error);
                        }
                    }
                }
            }).start();
        }
    });
    }

那么如何修复线程问题?

2个回答

biaoguo819
biaoguo819   2013.09.23 22:20

不能在线程中直接对result操作

ygycomon
ygycomon   Rxr 2013.09.24 09:44

网络io要另起线程用handler来操作

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!