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