Error displaying message

0
 public void iniciar() {

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {

            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;

            try {
                socket = new Socket(ip, 10000);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataInputStream = new DataInputStream(socket.getInputStream());
                dataOutputStream.writeUTF(valor);
                valorLido = dataInputStream.readLine();
                if (valorLido.equals("0")){
                    Toast.makeText(MainActivity.this, "Ambiente escuro! Lâmpada deve ser acesa!", Toast.LENGTH_LONG).show();
                    imageView = (ImageView) findViewById(R.id.imageView_Lampada);
                    imageView.setImageResource(R.drawable.lampada_acesa);
                }else{
                    Toast.makeText(MainActivity.this, "Ambiente claro! Lâmpada deve ser apagada!", Toast.LENGTH_LONG).show();
                    imageView = (ImageView) findViewById(R.id.imageView_Lampada);
                    imageView.setImageResource(R.drawable.lampada_apagada);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (socket != null) {
                        socket.close();
                    }
                    if (dataOutputStream != null) {
                        dataOutputStream.close();
                    }
                    if (dataInputStream != null) {
                        dataInputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    thread.start();

}

Does anyone know why it is giving error when running Toast.makeText?

    
asked by anonymous 13.08.2018 / 21:07

1 answer

1

Try to use:

        runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (valorLido.equals("0")){
                Toast.makeText(MainActivity.this, "Ambiente escuro! Lâmpada deve ser acesa!", Toast.LENGTH_LONG).show();
                imageView = (ImageView) findViewById(R.id.imageView_Lampada);
                imageView.setImageResource(R.drawable.lampada_acesa);
            }else{
                Toast.makeText(MainActivity.this, "Ambiente claro! Lâmpada deve ser apagada!", Toast.LENGTH_LONG).show();
                imageView = (ImageView) findViewById(R.id.imageView_Lampada);
                imageView.setImageResource(R.drawable.lampada_apagada);
            }
        }
    });

Android will not let you make changes to the view if you are not in Main Thread .

    
14.08.2018 / 18:35