This question is an exact duplicate:

I am engaged in creating a client server on sockets using java, with the peculiarity that in my case the client is an application written on android.
And if everything is fine with the server (I checked its work through telnet), then there are big problems with the client.
When trying to get a local host:
InetAddress ipAddress = InetAddress.getLocalHost();
It gives the following error (if through try-catch you are asked to output to the log):

android.os.NetworkOnMainThreadException

I connected the work with the network to the manifest file, but it did not help:
< uses-permission android:name="android.permission.INTERNET"/>
I rummaged through the forums, but I did not find a similar problem, so I’m contacting here :)

Reported as a duplicate by Sergey Gornostaev , post_zeew java 7 Jun '17 at 19:31 .

This question has been marked as a duplicate of an existing one.

  • one
    Google issues 60,900 pages for "NetworkOnMainThreadException", including a link to the official documentation. Specifically on ruSO search returns 32 results for the same query. - Sergey Gornostaev

2 answers 2

Your error code speaks for itself - it is impossible to use work with the network in the main thread.

You can run in a separate thread using Thread:

 Thread thread = new Thread(new Runnable() { @Override public void run() { try { //ваш код работы с сетью } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); 

You can allow work in the main thread (absolutely not recommended):

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); 

You can use AsyncTask :

 class RetrieveFeedTask extends AsyncTask<Void, Void, Void> { private Exception exception; protected RSSFeed doInBackground(Void... void) { try { //ваш код работы с сетью } catch (Exception e) { this.exception = e; return null; } } protected void onPostExecute(Void void) { // здесь можете обрабатывать ошибки при работе с сетью } } 
  1. About AsyncTask in Russian: AsyncTask Class
  2. About Thread in Russian: Flows. Thread class and Runnable interface
  • one
    and if in different methods you need to contact the server (for example, when you press a button, you need to send information from the form)? - nrjshka
  • @nrjshka can create AsyncTask connection stream and data send, another AsyncTask connection and data receive. You can write a unique AsyncTask / Service for these actions with processing all options of parameters)) If you are interested in the last option - I have a self-hosted Service with BroadcastReceiver that connect to the SQL server, perform the required insert / change / delete / get data and return the result .. But there it is done wonderfully)) - Evgen Orlovsky
  • And there are no more alternatives? It is necessary to contact the server in N-places and in general it is not clear how this can be implemented: D - nrjshka
  • @nrjshka can be done through Service - in my opinion the best option, although I often use AsyncTask for simple tasks. About services in Russian: developer.alexanderklimov.ru/android/theory/services-theory.php And don’t worry about N places - the stream worked and died, you don’t sweat when using String in 20 places in a class)) - Evgen Orlovsky
  • I agree, but I use it on the client and I need to contact the server constantly, without shutdowns - nrjshka

You cannot send requests from the main thread. Only through AsyncTask, as mentioned above :)

  • Absolutely not only through AsyncTask . Even more likely through it, in most cases, it is not recommended, due to possible memory leaks due to ignorance. - eugeneek