Skip to content Skip to sidebar Skip to footer

Android Tcp Client Read Socket In A Textview

I am developing a TCPclient for Android device. I can connect to a server and I can track that I receive message from the server. I would like to display the result sent by the se

Solution 1:

create a callback class,

interfaceSocketCallback {
  voidonReceived(String msg);
}

this can be an inner of ClientThread, as they are logically related. that's not required but it's good design.

have your Runnable class accept an instance of this callback in it's constructor.

publicClientThread(ClientThread.SocketCallback cb){
  this.callback = cb;
}

when you construct your Runnable (ClientThread), do so from your UI class (JssClientActivity), like this,

ClientThread ct = newClientThread(newClientThread.SocketCallback() {
  publicvoidonReceived(String msg) {
    JssClientActivity.this.runOnUiThread(newRunnable() {
      @Overridepublicvoidrun() {
        myTextView.setText(msg);
      }
    });
  }
}};

finally, in ClientThread, when you receive a message, call the callback,

while (-1 != val) {
  inMsg = in.readLine();
  this.callback.onReceived(inMsg);
}

note that you cannot update the UI from the thread where ClientThread is running. it must be updated from the UI thread, hence the call to runOnUiThread().

Solution 2:

You can set the text of a TextView by using the setText() method of it.

Example:

textview_textin.setText(yourText)

By using runOnUiThread() you will be able to access your TextView. See this answer.

Post a Comment for "Android Tcp Client Read Socket In A Textview"