Mokus
Mokus

Reputation: 10400

How can I change the view outside the main thread?

I would like to establish a client server connection between my phone and PC,

package com.example.tcptest;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

    TCPClient tcpclient;
    Boolean isconnected = false;
    Button connectBtn;
    Button sendBtn;
    TextView ipport;
    TextView sendtext;
    TextView rcvtext;
    Timer timer;

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

        //Buttons
        connectBtn=(Button)findViewById(R.id.connectbtn);
        sendBtn=(Button)findViewById(R.id.sendbtn);

        ipport = (TextView)findViewById(R.id.serverip);
        sendtext = (TextView)findViewById(R.id.sendtxt);
        rcvtext = (TextView)findViewById(R.id.console);      

        connectBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {   
                //String[] i_po = ((String)ipport.getText()).split(":");
                //tcpclint = new TCPClient(i_po[0], Integer.parseInt(i_po[1]));         

                Thread cThread = new Thread(new ClientThread());
                cThread.start();                
            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    public class ClientThread implements Runnable {     
        public void run() {
            tcpclient = new TCPClient("192.168.0.101", 5000);
            tcpclient.connect();
            tcpclient.send("hello server");
            rcvtext.setText(tcpclient.getdata());           
        }
    }

}

In this case i can't change the text of the rcvtext because it's running in thread, is there any possibilities to change the content of the rcvtext, if the connection was successful than I would like to write log to the rcvtext?

Upvotes: 1

Views: 1551

Answers (1)

Cat
Cat

Reputation: 67512

Within your ClientThread's run() method, implement this:

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        rcvtext.setText(tcpclient.getdata());
    }
});

That tells Android to run it on the UI thread (the main application thread) whenever it can, rather than the current thread.

Upvotes: 4

Related Questions