Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to fix android.os.NetworkOnMainThreadException error

Educative Answers Team
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


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();

Add the following permissions to manifest.xml file:

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


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring