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