Resolve the error android.os.NetworkOnMainThreadException in an android application that works as client to receive images of a server [duplicated]

0

I'm trying to make an Android application that fetches an image from the computer. The 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. But I can not do this. I still do not understand much from Android could someone help me to solve this problem? The error is related to threads, since I get this:

  

android.os.NetworkOnMainThreadException.

The code that I implemented on the client side, ie Android, is the following:

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() ;
            }   


        }
    });
  }
}
    
asked by anonymous 21.01.2015 / 17:35

1 answer

1

In Android the main thread (also called UI thread, or user interface ) is responsible for updating the graphical interface and therefore should be kept responsive, ie can not be taken by long operations such as data transmission operations over the network. These operations must be performed on a secondary thread. So the main thread throws this NetworkOnMainThreadException exception if you try to perform a network-related operation on it.

Search on AsyncTask . Here in Stack Overflow in Portuguese there are several examples.

    
21.01.2015 / 17:50