1. Recently, when learning to parse JSON data, an error message was encountered, as shown in the error message:
found that the parsed data is empty, error message as shown, found in the program of the Httputils tool class 22 line error and the Mainactivity class OnClick method 52 error occurred, so I went to look for the two class error in the row, to see if the code is wrong, Because I also study, so the code error is also very normal. The 22 lines of code in the 2.HttpUtils class are as follows: There is no wrong method to find, and then look at the 52 lines of the OnClick method of the Mainactivity class, as shown in: The discovery of this line of code is actually called the getjsoncontent of the Httputils class above ( Url_path) method, that I think should be the above through HttpURLConnection access to the network request may be error, so I surf the internet to find information, after testing the code is no problem. 3. Where does the problem arise? In fact, we found the code of the exception, but we did not print the full log of the exception information to see the whole, I once again attached to the log printed error message, a look will understand, as shown: The exception for the error is Android.os.NetworkOnMainThreadException exception, meaning that the Android operating system network work in the main thread exception, is in the network communication in the main thread of the work of the exception, so must work on another thread, so the above code is no problem, the problem is that the HTTP The Getjsoncontent (Url_path) method of the Utils class cannot be invoked on the main line thread, and must create a new thread for network operation, so we must be in the Mainactivity class of the onclick () Method calls the Getjsoncontent (Url_path) method and accesses it with a new thread for network communication. 4. So, we open up a new thread that is dedicated to the method that works on network communication to access the network. Even with a multithreaded approach, the 52 rows in the OnClick () method in the Mainactivity class can be changed to look like this: Sometimes the same error is reported, which is handled in the thread using the handle message mechanism.
Android via Httpurlconnection.getresponsecode status code throws an exception problem and workaround