Trusted answers to developer questions

How to fix android.os.NetworkOnMainThreadException error

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

svg viewer

The main reason this error occurs is because newer versions of android are very strict against UI thread abuse.

Every time an app is opened, a new “main” thread is created that is responsible for dispatching events to assigned widgets and helps applications interact with the running components of an app’s UI. When time-consuming actions are performed on the UI thread, it blocks the entire User Interface.

A NetworkOnMainThreadException is thrown when an app attempts to perform networking operations on the main thread. The error appears on all applications targeting Honeycomb SDK or higher. Applications are also not allowed to download files, perform HTTP requests, connect to remote MySQL database, or establish a socket connection.

svg viewer

Solution

The solution is to completely wrap any task that attempts to perform these actions into a separate async function. The async function creates a new thread, and therefore, the process does not run on the UI thread.

It is possible to override the instruction, however, that may make the application unresponsive and the task manager may have to kill the application. To override, add the following to the class where the user is performing network operations:

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

Add the following permissions to manifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>

RELATED TAGS

android
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?