How to fix android Os.NetworkOnMainThreadException?

By using AsyncTask (recommended)

import androidx.appcompat.app.AppCompatActivity; import android.os.AsyncTask; import android.os.Bundle; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; public class MainActivity extends AppCompatActivity { TextView textLoad, textMessage; final String strMessage = “https://sites.google.com/site/androidersite/text.txt”; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textLoad = findViewById(R.id.textLoad); textMessage = findViewById(R.id.textMessage); 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); }

Last Updated : 11 June, 2023

dot 1
/10

IT Quiz

Test your knowledge about topics related to technology

1 / 10

How many numbers of home pages a web site can contain

2 / 10

'.MOV' extension usually refers to what kind of file?

3 / 10

Who founded Microsoft?

4 / 10

Everyone knows what a robot is, but what is a 'cobot'?

5 / 10

'.BAK' extension usually refers to what kind of file?

6 / 10

What is the radix of the octal number system?

7 / 10

WWW Stands for

8 / 10

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

9 / 10

Which web browser is developed by the Google

10 / 10

Who is considered as the father of computing

Your score is

0%

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 *

Want to save this article for later? Click the heart in the bottom right corner to save to your own articles box!