[Solved] android.os.NetworkOnMainThreadException in API call [duplicate]


The exception that is thrown when an application attempts to perform a networking operation on its main thread. ref

So you need to move to move to a background process (thread):

Best way would be to use AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

So if you move this code to AsyncTask it should work.

URL url = new URL("https://api.myjson.com/bins/n80yl");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                try {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    bufferedReader.close();
                    Log.d("tagg", "onClick: "+stringBuilder);
                }catch (Exception e)
                {
                    Log.d("tagg", "onClick:exception1  "+e);
                }
                finally{
                    urlConnection.disconnect();
                }
            }
            catch(Exception e) {
                Log.d("tagg", "doInBackground:exception2 "+e);

            }

Don’t forget to add the internet permission to your Manifest.xml file

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

7

solved android.os.NetworkOnMainThreadException in API call [duplicate]