Android android.os.NetworkOnMainThreadException Error

Asked 2 years ago, Updated 2 years ago, 163 views

BlogsSearchResults results = null;

            try {
                String text = URLEncoder.encode(query, "UTF-8");
                String apiURL = blogSearchURL + text; // json Results
                apiURL += "&display=" + display + "&start=" + start + "&sort=" + sort;
                URL url = new URL(apiURL);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("X-Naver-Client-Id", clientId);
                con.setRequestProperty("X-Naver-Client-Secret", clientSecret);

                int responseCode = con.getResponseCode();
                BufferedReader br;
                If (responseCode == 200) { // Normal Call
                    br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                } else { // error occurred
                    br = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                }

                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = br.readLine()) != null) {
                    response.append(inputLine);
                }
                br.close();

                Gson gson = new Gson();
                results = gson.fromJson(response.toString(), BlogsSearchResults.class);
            } } catch (Exception e) {
                System.out.println(e);
            }

///////////////////// I'm currently studying Android, android.os.NetworkOnMainThreadException should be said to use thread for this error, but I don't understand exactly, so please explain it to me ㅠ<

android networkonmainthread thread-exceptions

2022-09-22 15:29

1 Answers

As the error states, network communication cannot be implemented on the main thread. This part should be implemented using AsyncTask or a different thread method. If you search for an error phrase on Google, you'll get several examples.


2022-09-22 15:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.