This question has already been answered:

The application contains 1 Activity , the onCreate method contains the following code:

  int c; URL myUrl = null; try { myUrl = new URL("http://www.pro-java.ru"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection myUrlCon = null; try { myUrlCon = myUrl.openConnection(); } catch (IOException e) { e.printStackTrace(); } long length = myUrlCon.getContentLength(); String data = ""; if(length != 0) { InputStream input = null; try { input = myUrlCon.getInputStream(); } catch (IOException e) { e.printStackTrace(); } try { while(((c = input.read()) != -1)) { data = data.concat(String.valueOf(c)); } } catch (IOException e) { e.printStackTrace(); } try { input.close(); } catch (IOException e) { e.printStackTrace(); } } 

Manifesto:

  <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.tcptest"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 

What can be caused by the departure?

Reported as a duplicate by post_zeew java Jul 31 '17 at 6:29 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 7
    The crystal ball says that you get a NetworkOnMainThreadException . - Sergey Gornostaev
  • 2
    @Andrey make work with the network in a separate thread, you can not do this in UIThread. - Lex Hobbit
  • Thank you all, I will try. - Andrei

1 answer 1

What can be caused by the departure?

It is caused by the fact that network operations cannot be performed in a UI stream. When working with a network in a UI thread, a NetworkOnMainThreadException will be NetworkOnMainThreadException .

In the simplest case, you can use AsyncTask , but it is better to use other tools for working with the Internet, which out of the box support work in threads other than UI, for example OkHttp . You can also use something like Rx , or, for example, Robospice or Chronos .

  • one
    Robospice has not been developing for the last 2 years, you shouldn’t watch it - DeKaNszn
  • one
    @DeKaNszn; It is already old, yes, but it copes with its tasks. - post_zeew
  • 2
    Yes, but not every person is able to independently apply patches with fixes from github issues - DeKaNszn