0

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?

12
  • what is the error/exception thrown back to you ? Add your stackTrace to the question Commented Apr 5, 2014 at 19:02
  • @SudhirMishra I am not quite sure how I get this Commented Apr 5, 2014 at 19:06
  • 2
    Make sure you are making the HTTP request in a separate thread, not on the UI thread. Commented Apr 5, 2014 at 19:06
  • @Cj1m every IDE has a LogCat. what error is logged in thate LogCat. Copy the error log only and add it here. Commented Apr 5, 2014 at 19:11
  • @KennyC is that the problem? Commented Apr 5, 2014 at 19:11

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

15 Comments

No, the JSON is valid
Ahh ok. Can you post the entire stacktrace?
Sorry, how do I do this, do you mean post everything in the logcat?
Yes post everything from the logcat for the app.
Ok, need to post on pastebin because it's too much for the comment section: pastebin.com/eHc4RSBc
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.