How to Fix "android.os.Network On Main Thread Exception error" in Android Studio?
Last Updated :
05 May, 2021
The main reason for Network On Main Thread Exception Error is because the newer versions of android are very strict against the UI thread abuse. Whenever we open an app, a new “main” thread is created which helps applications interact with the running components of an app’s UI and is responsible for dispatching events to assigned widgets. The entire User Interface is blocked when time-consuming actions are performed on the UI thread.
When an app attempts to perform networking operations on the main thread a Network On Main Thread Exception Error is thrown. The error shows on all applications targeting Honeycomb SDK or higher. Applications get disabled to download files, connect to remote MySQL database, perform HTTP requests or establish a socket connection.
Solutions
The solution is to completely wrap any task that attempts to perform actions like download files, connect to remote MySQL database, perform HTTP requests or establish a socket connection into a separate async function. A new thread is created by the async function, and hence, these processes do not run on the UI thread. We can also override the instruction, but in this situation, the task manager may have to kill the application and it will make the application unresponsive.
Solution 1
To overcome this situation, 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 the manifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
Solution 2
To solve this problem we will use a new Thread
Example:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
// Your code goes here
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
Solution 3
- Do not use strictMode (only in debug mode)
- Do not change the SDK version
- Do not use a separate thread
Solution 4
When an app attempts to perform networking operations on the main thread a Network On Main Thread Exception Error is thrown.
Example:
class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {
private Exception exception;
protected RSSFeed doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(RSSFeed feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
Solution 5
For the execution of the task in the MainActivity.java file, We will add this line within the onCreate() method
new RetrieveFeedTask().execute(urlToRssFeed);
and do not forget to add this to the AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
Similar Reads
Architecture of 8085 microprocessor A microprocessor is fabricated on a single integrated circuit (IC) or chip that is used as a central processing unit (CPU).The 8085 microprocessor is an 8-bit microprocessor that was developed by Intel in the mid-1970s. It was widely used in the early days of personal computing and was a popular cho
11 min read
Android Architecture Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
States of a Process in Operating Systems In an operating system, a process is a program that is being executed. During its execution, a process goes through different states. Understanding these states helps us see how the operating system manages processes, ensuring that the computer runs efficiently. Please refer Process in Operating Sys
11 min read
Android Tutorial In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Activity Lifecycle in Android with Demo App In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Android Development Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
Android UI Layouts Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
Top 50 Android Interview Questions and Answers - SDE I to SDE III A Linux-based open-source OS, Android was created by Andy Rubin and became one of the most popular smartphone operating systems. With 71 percent of the market share worldwide, Android is on top. Because it is on top in the smartphone OS, Android development is always in demand.If you are seeking a j
15+ min read
Components of an Android Application There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the appâs metadata, its hardware confi
3 min read
Top 50 Flutter Interview Questions and Answers for 2025 Flutter is an open-source, cross-platform application development framework. It was developed by Google in 2017. It is used to build applications for Android, iOS, Linux, Mac, Windows, and the web. Flutter uses the Dart programming language. It provides a simple, powerful, efficient, and easy-to-und
15+ min read