Logo pl.removalsclassifieds.com

Jak naprawić wyjątek android.os.NetworkOnMainThreadException?

Anonim

Za pomocą AsyncTask (zalecane)

importuj androidx.appcompat.app.AppCompatActivity; importuj android.os.AsyncTask; importuj android.os.Bundle; importuj android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; importuj java.net.URL; public class MainActivity extends AppCompatActivity { TextView textLoad, textMessage; końcowy String strMessage = „https://sites.google.com/site/androidersite/text.txt”; @Zastąp chronione void onCreate(Bundle protectedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textLoad = findViewById(R.id.textLoad); textMessage = findViewById(R.id.textMessage); textLoad.setText(„Ładowanie…”); nowe MojeZadanie().execute(); } private class MyTask extends AsyncTask{ String wynik; @Zastąp chronione Void doInBackground(Void… voids) { URL url; spróbuj { url = nowy adres URL(strMessage); BufferedReader bufferedReader = new BufferedReader(nowy InputStreamReader(url.openStream())); String stringBuffer; Ciąg znaków = „”; while ((stringBuffer = bufferedReader.readLine()) != null){ string = String.format(“%s%s”, string, stringBuffer); } bufferedReader.close(); wynik = ciąg; } catch (IOException e){ e.printStackTrace(); wynik = e.toString(); } return null; } @Zastąp chronione void onPostExecute(Void aVoid) { textMessage.setText(result); textLoad.setText("Zakończono"); super.onPostExecute(unieważnij); } } }

Wyłącz tryb ścisły (niezalecane)

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

Jak naprawić wyjątek android.os.NetworkOnMainThreadException?