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

Related :   Use repo on Windows to download android source

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


lynxbee_ezoic

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


Leave a Comment

Android Android Applications Android Build system Android Commands Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded