Search code examples
javaandroidudprunnable

How to run a Textview on runnable


I have this following code, the problem that i read is that you cannot place a textview inside a runnable method, how can i implement this one.

Thread UDPreceive;
    Handler handler = new Handler();
    void startListen() {
        UDPreceive = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while(true) {
                        String hey;
                        //TextView text22 = (TextView) findViewById(R.id.textView2);
                        int server_port = 9875;
                        byte[] message = new byte[255];
                        DatagramPacket p = new DatagramPacket(message, message.length);
                        DatagramSocket s = new DatagramSocket(server_port);
                        s.receive(p);
                        hey = new String(message, 0, p.getLength());
                        Log.d("MESSAGE: ", "Message is:" + hey);
                        //text22.setText(hey);
                        s.close();
                    }
                } catch (Exception e) {
                    System.err.println(e);
                    e.printStackTrace();
                }
            }

        });
        UDPreceive.start();

    }

Solution

  • Yo can also use 
    
    runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    text22.setText(hey);
                                }
                            });
    
    It will give you main thread access to render on UI.