Hello friends, I have seen so many new developers facing a specific error android.os.NetworkOnMainThreadException

Why this android crash happened

Main this application crash happened on Android’s Honeycomb(3.0) and above, but it’s works fine on Android’s older versions(2.x). Its because Honeycomb(3.0) and above that version are much stricter about abuse against the UI Thread. For example, when an Android device running 3.0 or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown:

Solution of this crash


Creating New Android Project

So let’s start by creating a new android project

1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project. I had left my main activity name as MainActivity.java and gave the package name as info.androidstation.networkonmainthread

2. As we are fetching the Data by making HTTP calls, we need to add INTERNET permission in our AndroidManifest.xml file. Open AndroidManifest.xml and add the following permission.

3. We are also checking weather the internet is available or not? We need to add ACCESS_NETWORK_STATE permission in our AndroidManifest.xml file. Open AndroidManifest.xml and add the following permission.


4. We are now creating a Utility class called Utility.java. In this class we will check weather internet is available or not? We will also download data from the url using GET method and after that we will read all the downloaded data and convert it into simple string.


5. I am adding a TextView to show the downloaded data. Open the layout file of your main activity and add a TextView element.


6. In main activity class (MainActivity.java) I have declared things; one inner class extends AsyncTask and another one is function. Asynctask will call the downloadData function of Utility class in doInBackground override method it’s the separate thread which will not affect to the UI thread. while function directly call the downloadData function from the UI thread so this will throw exception.


This Example Output Will look like this:

Hope you all find this tutorial useful. Happy coding. 🙂