javaandroidjava.util.scanneroutputstreamdatainputstream

My client code makes my android app crash


So I have this client code which I tested in Eclipse and it works there

try {
    // Establish connection
    Socket socket = new Socket(InetAddress.getByName("192.168.1.104"), 9000);

    // Request data
    OutputStream outputStream = socket.getOutputStream();
    InputStream inputStream = socket.getInputStream();

    msg = "IDGN:" + "1";
    System.out.println(msg);

    outputStream.write(msg.getBytes());
    socket.shutdownOutput();
    scanner = new DataInputStream(inputStream);
    restaurante = scanner.readUTF();
    System.out.println(restaurante);

    // Shut down socket
    socket.shutdownInput();
    socket.close();
} catch (IOException io) {
    io.printStackTrace();
}

But when I try to do the same in an Android app it crashes

try {
    // Establish connection
    Socket socket = new Socket(InetAddress.getByName("192.168.1.104"), 9000);

    // Request data
    OutputStream outputStream = socket.getOutputStream();
    InputStream inputStream = socket.getInputStream();

    msg = "IDGN:" + "1";
    outputStream.write(msg.getBytes());
    socket.shutdownOutput();

    scanner = new DataInputStream(inputStream);
    restaurante = scanner.readUTF();

    View b = findViewById(R.id.texto);
    b.setVisibility(View.VISIBLE);
    String ss = "Valore el servicio recibido en: " + restaurante;
    ((TextView) b).setText(ss);

    // Shut down socket
    socket.shutdownInput();
    socket.close();
} catch (IOException io) {
    io.printStackTrace();
}

I just don't know why and I have tried to make it wait for the data to be ready, to change it to OutputStream and read a line from a scanner, to read the bytes directly from the OutputStream.

The Server seems to be receiving the Data fine in both cases (Android and Eclipse) and sending the correct answer.


Solution

  • You cannot have both network I/O and UI operations such as TextView#setText() in the same thread. Attempting to do network I/O on UI thread results in NetworkOnMainThreadException. Attempting to do UI operations on non-UI thread results in CalledFromWrongThreadException. Guess your code is crashing on one of these.

    There are some advanced mechanism for threading such as rxjava schedulers or kotlin coroutines. Without adding additional library dependencies you could experiment moving your network code to an AsyncTask.

    See also:

    How do I fix android.os.NetworkOnMainThreadException?

    Unfortunately MyApp has stopped. How can I solve this?