Cj1m
Cj1m

Reputation: 815

Parsing JSON From URL In Android

I am trying the parse the following JSON in android - http://cj1m.1.ai/test.json

At the moment, when running this code, my app crashes:

public String getJSON() throws IOException{
    String url = "http://cj1m.1.ai/test.json";

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
    String jsonText = reader.readLine();

    return jsonText;
}

What am I doing wrong, and how can I fix this?

Upvotes: 0

Views: 112

Answers (1)

Naveen
Naveen

Reputation: 1060

The issue might be because of incorrect JSON response format. Looks like the JSON response is incorrect in http://cj1m.1.ai/test.json. You can validate your JSON response in this URL - http://jsonlint.com/

Edit:

From your latest log, it is clear that you are trying to retrieve the JSON in the main thread which causes the app to crash. You need to make use of AsyncTask to perform network operations.

You can refer this code,

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

More details here!

Hope this helps.

Upvotes: 1

Related Questions