How to fix android Os.NetworkOnMainThreadException?

By using AsyncTask (recommended)


IT Quiz

Test your knowledge about topics related to technology

1 / 10

The core idea of develop AI is bulding machines and alogrithms to

2 / 10

AI systems are made up of

3 / 10

Firewall in computer is used for

4 / 10

The output printed by a computer through a printer on the paper is called

5 / 10

Which web browser is developed by the Google

6 / 10

The intention of Machine Learning is

7 / 10

The app or software, or website asks about access of your location, camera, storage, contacts etc., are known as

8 / 10

Which is an Input device

9 / 10

Systems for differently-abled individuals is an example of

10 / 10

Which of the following AI domain attempts to extract information from spoken and written words using algorithms?

Your score is


import; import android.os.AsyncTask; import android.os.Bundle; import android.widget.TextView; import; import; import; import; public class MainActivity extends AppCompatActivity { TextView textLoad, textMessage; final String strMessage = “”; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textLoad = findViewById(; textMessage = findViewById(; textLoad.setText(“Loading…”); new MyTask().execute(); } private class MyTask extends AsyncTask{ String result; @Override protected Void doInBackground(Void… voids) { URL url; try { url = new URL(strMessage); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); String stringBuffer; String string = “”; while ((stringBuffer = bufferedReader.readLine()) != null){ string = String.format(“%s%s”, string, stringBuffer); } bufferedReader.close(); result = string; } catch (IOException e){ e.printStackTrace(); result = e.toString(); } return null; } @Override protected void onPostExecute(Void aVoid) { textMessage.setText(result); textLoad.setText(“Finished”); super.onPostExecute(aVoid); } } }

Disable Strict Mode (Not recommended)

if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }

One request?

I’ve put so much effort writing this blog post to provide value to you. It’ll be very helpful for me, if you consider sharing it on social media or with your friends/family. SHARING IS ♥️

Leave a Comment

Your email address will not be published. Required fields are marked *