How to catch a JSON from a URL?

Asked

Viewed 2,410 times

4

I continue studying Androidstudio and the ball of turn eh catch data by URL, in json format,

For that reason created an example page:
(http://exemplo.minha.info/nav/2.html),

with the following content:
{"content": "hello world"}

THEN I took the example from here: https://stackoverflow.com/questions/32549360/best-practice-to-get-json-from-url-in-api-23

Where my code was like this:

//  public class JSONParser {
    public static class JSONParser {
    
        static InputStream is = null;
        static JSONObject json = null;
        static String output = "";



        public JSONObject getJSONFromUrl(String url, List params) {
            URL _url;
            HttpURLConnection urlConnection;

            try {
                _url = new URL(url);
                urlConnection = (HttpURLConnection) _url.openConnection();
            }
            catch (MalformedURLException e) {
                Log.e("JSON Parser", "Error due to a malformed URL " + e.toString());
                return null;
            }
            catch (IOException e) {
                Log.e("JSON Parser", "IO error " + e.toString());
                return null;
            }

            try {
                is = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder total = new StringBuilder(is.available());
                String line;
                while ((line = reader.readLine()) != null) {
                    total.append(line).append('\n');
                }
                output = total.toString();
            }
            catch (IOException e) {
                Log.e("JSON Parser", "IO error " + e.toString());
                return null;
            }
            finally{
                urlConnection.disconnect();
            }

            try {
                json = new JSONObject(output);
            }
            catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            return json;
        }
    }



And, I’m calling the code from the "onCreate" like this:

JSONParser jsonParser = new JSONParser();
JSONObject payload = jsonParser.getJSONFromUrl(
        "http://igakubu.e4dev.info/nav/2.html",
        null);
try {
    System.out.println(payload.get("content"));
} catch (JSONException e) {
    e.printStackTrace();
}

Turns out it gives an error in the line
"is = new Bufferedinputstream(urlConnection.getInputStream());"

with the following code on the console:
at jp.co.e_grid.rakuseki.Postconfirmationactivity$Jsonparser.getJSONFromUrl(Postconfirmationactivity.java:177)



and from here.. I was completely lost, the more I could google, eh that seems to be a java error.

I’d appreciate it if someone gave me a north here, because I’m new!

1 answer

3


android.os.Networkonmainthreadexception

The exception that is thrown when an application tries to run a network operation in its core segment.

To avoid this error, try using the AsyncTask. And put all network-related tasks within the method doInBackground of your AsyncTask.

I suggest you read a little more about Synchronous x Asynchronous data communication. Right here at Sopt has this question about the difference between asynchronous and synchronous communication with some very enlightening answers that will help you greatly.

Example of AsyncTask:

public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }
    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            JSONParser.getJSONFromUrl(URL); 

            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
    }
}

Soon after you can call the class inside your onCreate in this way:

new JSONAsyncTask().execute(URL);

Remembering that there are several ways to do this besides using the AnsyncTask. I also suggest you read a little more consume data from an Android Web Service.

  • ui! brigade! studying! : D you are always attentive! happy here ! PS* I had to "pause" the other post (permission to use GPS) but I’ll be right back for it!

  • @Camilayamamoto no problem. I will detail more this answer for you, but while reading the links to better understand.

  • well I’ll try! on page.... https://developer.android.com/reference/android/AsyncTask.html I’m having a hard time understanding what to put on (URL... urls)

  • @Camilayamamoto I’ll put an example consuming your 2.html for you. just a minute.

  • I got it! : D !

  • @Camilayamamoto if you want to do a test, it already works.

  • I’m sorry to bother you, but... I have some doubts here.. like: my Andriodstudio imports the "Asynctask" without problems... but .. already the "Httpget " it requires that I create a class?? that is anyway anyway?

  • @Camilayamamoto in fact the use of Async is this way ai without more. The values that are inside theInBackground are to rescue data from what is on your html page. This httpGet is already deprecated, but it still works well. I put so that you had more notion. To import this library, go to Gradle and inside Android useLibrary 'org.apache.http.legacy' and ask to sync.

  • I made an update, in question.... inserting your answer and what you gave me back! still appears the same error! so I didn’t need to use (http deprecached)

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.