-1

I'm trying to send a string from my phone to my Computer via UDP. In the emulator, everything works fine, I can send the string and I can receive the message on my Computer with the server-side program.

Whenever I install the apk on my phone and try to send a message, it crashes at the line:

try {udpSocket = new DatagramSocket(Integer.parseInt(String.valueOf(tPort.getText()))); } catch (Exception e) {;}

tPort has the port written in it. tIP has the IP in it.

I request this permission in the manifest:

<uses-permission android:name="android.permission.INTERNET" />

Hope somebody can spot the mistake.

I'm running the app in the emulator on a Pixel 3 XL and I have a Pixel 3a as my physical phone.

package com.example.message;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.*;
import java.net.*;

import android.view.View;
import android.widget.TextView;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    TextView tLog,tIP,tPort, tEnter;
    Button send;
    DatagramSocket udpSocket;

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

        tLog = (TextView) findViewById(R.id.tLog);
        tIP = (TextView) findViewById(R.id.tIP);
        tPort = (TextView) findViewById(R.id.tPort);
        tEnter = (TextView) findViewById(R.id.tEnter);
        send = (Button) findViewById(R.id.bSend);


        send.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                tLog.setText("sending...");
                try {
                    try {udpSocket = new DatagramSocket(Integer.parseInt(String.valueOf(tPort.getText()))); } catch (Exception e) {;}
                    InetAddress serverAddr = InetAddress.getByName(String.valueOf(tIP.getText()));
                    byte[] buf = (String.valueOf(tEnter.getText())).getBytes();
                    DatagramPacket packet = new DatagramPacket(buf, buf.length,serverAddr, Integer.parseInt(String.valueOf(tPort.getText()))); //9876
                    udpSocket.send(packet);
                    tLog.setText("successfully sent message!");
                } catch (Exception e) {
                    tLog.setText("couldn't send message...");
                }
            }
        });

    }

}

The program crashes with this:

android.os.NetworkOnMainThreadException

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • Possible duplicate of [How to solve NetworkOnMainThreadException error in android?](https://stackoverflow.com/questions/15188810/how-to-solve-networkonmainthreadexception-error-in-android) – Phantômaxx Jul 15 '19 at 17:39

1 Answers1

0

Okay, I have found a solution. While it seemed to work on other devices, my phone didn't want to send the message. I now moved the whole process into a new Thread and now it works fine.