Come risolvere android.os.NetworkOnMainThreadException?

Utilizzando AsyncTask (consigliato)

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 estende AppCompatActivity { TextView textLoad, textMessage; final String strMessage = "https://sites.google.com/site/androidersite/text.txt"; @Override protected void onCreate(Bundle saveInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textLoad = findViewById(R.id.textLoad); textMessage = findViewById(R.id.textMessage); textLoad.setText(“Caricamento in corso…”); new MyTask().execute(); } La classe privata MyTask estende AsyncTask{ Risultato stringa; @Override protected Void doInBackground(Void… voids) { URL url; prova { url = nuovo URL (strMessage); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); Stringa stringaBuffer; Stringa stringa = “”; while ((stringBuffer = bufferedReader.readLine()) != null){ string = String.format(“%s%s”, string, stringBuffer); } bufferedReader.close(); risultato = stringa; } catch (IOException e){ e.printStackTrace(); risultato = e.toString(); } restituisce null; } @Override protected void onPostExecute(Void aVoid) { textMessage.setText(result); textLoad.setText(“Finito”); super.onPostExecute(aVoid); } } }

Disabilita la modalità rigorosa (non consigliata)

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

x
2D vs 3D