How to fix android.os.NetworkOnMainThreadException?

By using AsyncTask (recommended)

import; import android.os.AsyncTask; import android.os.Bundle; import android.widget.TextView; import; import; import; import; public class MainActivity extends AppCompatActivity { TextView textLoad, textMessage; final String strMessage = “”; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textLoad = findViewById(; textMessage = findViewById(; textLoad.setText(“Loading…”); new MyTask().execute(); } private class MyTask extends AsyncTask{ String result; @Override protected Void doInBackground(Void… voids) { URL url; try { url = new URL(strMessage); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); String stringBuffer; String string = “”; while ((stringBuffer = bufferedReader.readLine()) != null){ string = String.format(“%s%s”, string, stringBuffer); } bufferedReader.close(); result = string; } catch (IOException e){ e.printStackTrace(); result = e.toString(); } return null; } @Override protected void onPostExecute(Void aVoid) { textMessage.setText(result); textLoad.setText(“Finished”); super.onPostExecute(aVoid); } } }

Disable Strict Mode (Not recommended)

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

AskAnyDifference HomeClick here
Search for "Ask Any Difference" on Google. Rate this post!
[Total: 0]
One request?

I’ve put so much effort writing this blog post to provide value to you. It’ll be very helpful for me, if you consider sharing it on social media or with your friends/family. SHARING IS ♥️

Notify of
Inline Feedbacks
View all comments