-2

I want to connect an android app to a server with java's ServerSocket and Socket classes. I am using the following line at the client to connect to the server:

var socket = new Socket(InetAddress.getByName("192.168.1.21"), 59090);

("192.168.1.21" is my computer's ip) Now, when I'm opening a simple java project file it is working, but when I'm trying this line in an android project and I run it through a simulator it throws the said exception and crashes. the associated stack trace Does anybody know why?

Gilad Deutsch
  • 365
  • 3
  • 9

2 Answers2

1

The stack trace shows the problem is that a NetworkOnMainThreadException was thrown.

The documentation for that exception says you can't do network operations on your main thread.

As for how I knew where to look: the stack trace says that the IllegalStateException was caused by an InvocationTargetException which was caused by a NetworkOnMainThreadException.

1

you need to create AsyncTask and create new Socket within AsyncTask. You can't make a network call inside UI main thread.

Don Ha
  • 689
  • 5
  • 9