[Solved-4 Solutions] How to fix android.os.NetworkOnMainThreadException ?
Error Description:
- Error while running an Android project for RssReader
Code:
- And it shows the below error:
Solution 1:
- This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:
How to execute the task:
In MainActivity.java file we can add this line within the oncreate() method
- Don't forget to add this to AndroidManifest.xml file:
Solution 2 :
- You should almost always run network operations on a thread or as an asynchronous task. But if you know better and are willing to accept the consequences, and must do network operations on the main thread, you can override the default behavior:
Add:
- In your class, ADD this permission in android manifest.xml file:
Consequences:
- Your app will (in areas of spotty internet connection) become unresponsive and lock up, the user perceives slowness and has to do a force kill, and you risk the activity manager killing your app and telling the user that the app has stopped.
- Android has some good tips on good programming practices to design for responsiveness.
Solution 3:
Solution 4 :
- Do not use strictMode (only in debug mode)
- Do not change SDK version
- Do not use a separate thread
Use Service or AsyncTask