0

I have a TCP Client running in a Thread. Now I am getting Messages from the TCP Server. The Messages are saved as an int variable.

At the Moment I am using prinln method to see the Messages.

But I would like to Show that on the GUI. How can I do that?

mosambers
  • 21
  • 1
  • 7

3 Answers3

0

There are many ways to do this. One simple way of doing this is as-

new Handler().post(new Runnable() {
    @Override
    public void run() {
        // Code here will run in UI thread
    }
});

for more info see this Android basics: running code in the UI thread

Community
  • 1
  • 1
Vikash Kumar Verma
  • 1,068
  • 2
  • 14
  • 30
0

Use runOnUiThread and call setText inside.

runOnUiThread(new Runnable() {
           @Override
               public void run() {
                   a.setText("text");
         }
 });
DAVIDBALAS1
  • 484
  • 10
  • 31
0

To update UI from thread .

  1. you can use runOnUiThread as DAVIDBALAS1 told you
  2. also you can use handler as Vikash Kumar Verma told you you can also send data by useing sendMessage() to handle like

    new Thread(new Runnable() {
        @Override
        public void run() {
    
            final Message msg = new Message();
            final Bundle b = new Bundle();
            b.putInt("KEY", value);
            msg.setData(b);
            handler.sendMessage(msg);    
        }
    ).start();
    
    
    
    
    // Handle Message in handleMessage method of your controller (e.g. on UI      thread)
    handler = new Handler() { 
        @Override
        public void handleMessage(Message msg) {
            Bundle b = msg.getData();
            Integer value = b.getInt("KEY");
    
            textView.setText(""+value );
        }
    };
    
  3. you can use asynctask like

    private class LongOperation extends AsyncTask {

    @Override
    protected String doInBackground(String... params) {
        for (int i = 0; i < 5; i++) {
            try {
    
           //Perform long running task here and 
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.interrupted();
            }
        }
        return "Executed";
    }
    
    @Override
    protected void onPostExecute(String result) {
    
        //here you can update UI this work on UI thread
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText("Executed"); // txt.setText(result);
        // might want to change "executed" for the returned string passed
        // into onPostExecute() but that is upto you
    }
    
    @Override
    protected void onPreExecute() {}
    
    @Override
    protected void onProgressUpdate(Void... values) {}
    

    }

  4. you can also use BroadcastReceiver to update UI (mostly used in service to update UI from service) As explain by my this friend - https://stackoverflow.com/a/14648933/4741746

Community
  • 1
  • 1
Sushant Gosavi
  • 3,647
  • 3
  • 35
  • 55