The easiest way to fix android.os.NetworkOnMainThreadException
If you just want to fix the android.os.NetworkOnMainThreadException error, skip to step 3 ^^
1. Concept.
-. When developing Android, I often see an error message called android.os.NetworkOnMainThreadException.
The above error occurs when network-related APIs are used directly in Android's basic activity.
This concept is a limitation applied in most operating systems.
For example, even in windows development called .net, in form (the concept of activity in Android)
If you use the network API, a stop (UserInterface stuck) occurs.
2. Possible Solutions
-. The network must be used in a separate process (thread) from the user interface (actions such as pressing a button) used by the user.
In other words, it can be solved by creating a separate Thread and using the Network (Http, etc.) API.
3. Workaround
-. Sharing the simplest solution is as follows.
In MainActivity, in the place where you want to use Network operation, enter as below.
Before, when the code below is executed, a NetworkOnMainThreadException error occurs.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getXmlData(); // network operation, code to get xml from internet
}
After, if you process new thread as below, it will be solved without error. This is the code with the red code added.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(() -> {
getXmlData(); // network operation, code to get xml from internet
}).start();
}
I haven't seen a simpler solution than this. ^^
I hope you have fun coding.
4. what is networkonmainthreadexception?
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.
have a good day.
Comments
Post a Comment