How to get a JSON, from a URL?

4

I'm still studying AndroidStudio and it's time to get data by URL, in json format,

  

To do this I created an example page:
  ( link ),

     

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

THEN I took the example here: link

Where my code looks 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();
}

It turns out that there is an error on the line
"is = new BufferedInputStream (urlConnection.getInputStream ());"

with the following code in the console:
at jp.co.e_grid.rakuseki.PostConfirmationActivity $ JSONParser.getJSONFromUrl (PostConfirmationActivity.java:177)


and from here .. I was completely lost, the most I could search on google, and that seems to be a java error.

I would appreciate it if someone gave me a north here, because I'm novice!

    
asked by anonymous 27.01.2017 / 02:02

1 answer

2

android.os.NetworkOnMainThreadException

  

The exception that is thrown when an application tries to perform a   network operation in its main thread.

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

I suggest you read a little more about Synchronous vs. Asynchronous Data Communication . Right here in SOpt has this question about

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) {
    }
}

Then you can call the class inside your onCreate like this:

new JSONAsyncTask().execute(URL);

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

    
27.01.2017 / 02:10