Bagaimana cara memperbaiki android.os.NetworkOnMainThreadException?

Dengan menggunakan AsyncTask (disarankan)

impor androidx.appcompat.app.AppCompatActivity; impor android.os.AsyncTask; impor android.os.Bundle; impor android.widget.TextView; impor java.io.BufferedReader; impor java.io.IOException; impor java.io.InputStreamReader; impor java.net.URL; MainActivity kelas publik memperluas AppCompatActivity { TextView textLoad, textMessage; string terakhir 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(“Memuat…”); baru MyTask().execute(); } kelas pribadi MyTask memperluas AsyncTask{ Hasil string; @Override protected Void doInBackground(Void… voids) { URL url; coba { url = URL baru(strMessage); BufferedReader bufferedReader = BufferedReader baru(InputStreamReader baru(url.openStream())); String stringBuffer; String string = “”; while ((stringBuffer = bufferedReader.readLine()) != null){ string = String.format(“%s%s”, string, stringBuffer); } bufferedReader.close(); hasil = string; } catch (IOException e){ e.printStackTrace(); hasil = e.toString(); } mengembalikan nol; } @Override protected void onPostExecute(Void aVoid) { textMessage.setText(result); textLoad.setText("Selesai"); super.onPostExecute(hindari); } } }

Nonaktifkan Mode Ketat (Tidak disarankan)

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

x
2D vs 3D