Find the latest bookmaker offers available across all uk gambling sites www.bets.zone Read the reviews and compare sites to quickly discover the perfect account for you.
Sunday , 22 January 2017

How to resolve android.os.NetworkOnMainThreadException

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.

AndroidManifest.xml

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.

Utility.java

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

activity_main.xml

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.

MainActivity.java

This Example Output Will look like this:

android.os.NetworkOnMainThreadException
Hope you all find this tutorial useful. Happy coding. 🙂

Share

Leave a Reply

Your email address will not be published. Required fields are marked *