Como corrigir android.os.NetworkOnMainThreadException?

Usando AsyncTask (recomendado)

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; tente {url = novo URL (strMessage); BufferedReader bufferedReader = novo BufferedReader (novo InputStreamReader (url.openStream ())); String stringBuffer; String string = “”; while ((stringBuffer = bufferedReader.readLine ())! = null) {string = String.format (“%s%s”, string, stringBuffer); } bufferedReader.close (); resultado = string; } catch (IOException e) {e.printStackTrace (); resultado = e.toString (); } return null; } @Override protected void onPostExecute (Void aVoid) {textMessage.setText (resultado); textLoad.setText (“Concluído”); super.onPostExecute (aVoid); }}}

Desative o modo estrito (não recomendado)

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