Solved: System.out: android.os.NetworkOnMainThreadException

In Android application, if you are doing some network operations like download from some external website or share some data with someone etc, and if by unknowingly if we tries to do such network calls on any activities main thread, Android reports an “network on main thread” exception errors as below,

System.out: android.os.NetworkOnMainThreadException
System.out:    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java)

Solution : The appropriate solution to this problem is to avoid the network operations in the main activity thread, and if at all you can not avoid network operations on main thread, use Async Tasks and do the network calls in “doInBackground” API of AsyncTask. Example of Async Task is at https://developer.android.com/reference/android/os/AsyncTask

Second Solution ( Temporary work-around)

If for any reason like, time constraints or complexity of code etc, you can’t implement Async Tasks immediately, then you can disable the strict mode as,

import  android.os.StrictMode;
protected void onCreate(Bundle savedInstanceState) {

                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
}

Reference : https://developer.android.com/reference/android/os/StrictMode.ThreadPolicy.html

Leave a Comment