Resolve android.os.Networkonmainthreadexception error in an android application that works as a client to receive images from a server

Asked

Viewed 352 times

0

I’m trying to make an Android app that will fetch an image from the computer. Server-side code (computer) is already implemented and operational. Using UDP, I ask the server to send me an image and it responds with that same image. However, I am not able to do this. Still don’t know much about Android anyone could help me solve this problem? The error is related to threads since I get this:

android.os.Networkonmainthreadexception.

The client-side code I implemented, or Android, is as follows::

public class MainActivity extends ActionBarActivity {

  private final static int PACKETSIZE = 9000 ;
  public static final int SERVERPORT = 8777;
  public static final int CLIENTPORT = 8667;

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

    Button botao1;
    botao1 = (Button)findViewById(R.id.button1);

    botao1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            DatagramSocket socket = null ;

            try
            {
                InetAddress IPAddress = InetAddress.getByName("193.x.x.x");

                // Construção do socket
                socket = new DatagramSocket(CLIENTPORT) ;

                // Construção do pacote datagrama
                String msg = "imagem.jpg";
                byte [] data = msg.getBytes() ;
                DatagramPacket packet = new DatagramPacket(data, data.length, IPAddress, SERVERPORT) ;

                // Envio do pacote
                socket.send(packet) ;
                Log.d("UDP", "A enviar o pedido da imagem...");

                //Preparação da Data para recepção
                packet.setData(new byte[PACKETSIZE]);

                // Espera por uma resposta do Servidor
                socket.receive(packet) ;
                Log.d("UDP", "Imagem recebida...");

                byte[] bytearray = packet.getData();
                Log.d("UDP", " Data armazenada num bytearray");
                final Bitmap new_img = BitmapFactory.decodeByteArray(bytearray, 0,bytearray.length);
                ImageView image = (ImageView) findViewById(R.id.imageView1);
                image.setImageBitmap(new_img);

            }
            catch(Exception e)
            {
                System.out.println(e) ;
            }
            finally
            {
                if(socket != null)
                    socket.close() ;
            }   


        }
    });
  }
}

1 answer

1

On Android the main thread (also called UI thread, or user interface) is responsible for updating the graphical interface and therefore should be kept responsive, that is, it cannot be taken over by long operations such as network data transmission operations. These operations must be performed on a secondary thread. That’s why the main thread throws this exception NetworkOnMainThreadException if you try to run a network related operation on it.

Search on AsyncTask. Right here in Stack Overflow in English you have several examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.