Logo fr.removalsclassifieds.com

Comment réparer android.os.NetworkOnMainThreadException ?

Anonim

En utilisant AsyncTask (recommandé)

importer androidx.appcompat.app.AppCompatActivity; importer android.os.AsyncTask; importer android.os.Bundle; importer android.widget.TextView; importer java.io.BufferedReader; importer java.io.IOException; importer java.io.InputStreamReader; importer java.net.URL; La classe publique MainActivity étend AppCompatActivity { TextView textLoad, textMessage; chaîne finale strMessage = "https://sites.google.com/site/androidersite/text.txt"; @Override protected void onCreate(Bundle protectedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textLoad = findViewById(R.id.textLoad); textMessage = findViewById(R.id.textMessage); textLoad.setText("Chargement…"); new MyTask().execute(); } la classe privée MyTask étend AsyncTask{ String result; @Override protected Void doInBackground (Void… voids) { URL url; essayez { url = nouvelle URL (strMessage); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); String stringBuffer; Chaîne chaîne = ""; while ((stringBuffer = bufferedReader.readLine()) != null){ string = String.format(“%s%s”, string, stringBuffer); } bufferedReader.close(); résultat = chaîne; } catch (IOException e){ e.printStackTrace(); résultat = e.toString(); } renvoie null; } @Override protected void onPostExecute(Void aVoid) { textMessage.setText(result); textLoad.setText("Terminé"); super.onPostExecute(aVoid); } } }

Désactiver le mode strict (non recommandé)

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

Comment réparer android.os.NetworkOnMainThreadException ?