Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Have an error on jsonObject

I'm learning in Parsing Data Returned in JSON Format Android Course

When i run program i found an error in Logcat

org.json.JSONException: Unterminated object at character 5728

my code : https://gist.github.com/lifez/7008441 Screenshot : http://imgur.com/a/alvBV

2 Answers

Please help

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

Hi Phawin,

Sorry about this! It is a known error...we discussed this in the Forum a while back and have linked to it as a "Known Issue" in the Teacher Notes on the video page. Check out the solution (and discussion) in that other thread.

Other posts about this issue:

https://teamtreehouse.com/forum/parsing-data-returned-in-json-jsonexception-unterminated-string-at-character-5792 https://teamtreehouse.com/forum/trying-to-retrieve-data-from-my-own-blog-help

Try replacing the whole doInBackground method with this version:

@Override
protected JSONObject doInBackground(Object... params) {
    int responseCode = -1;
    JSONObject jsonResponse = null;
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://www.grepscience.com/api/get_recent_summary/");

    try {
        HttpResponse response = client.execute(httpget);
        StatusLine statusLine = response.getStatusLine();
        responseCode = statusLine.getStatusCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while((line = reader.readLine()) != null){
                builder.append(line);
            }

            jsonResponse = new JSONObject(builder.toString());
        }
        else {
            Log.i(TAG, String.format("Unsuccessful HTTP response code: %d", responseCode));
        }
    }
    catch (JSONException e) {
        logException(e);
    }
    catch (Exception e) {
        logException(e);
    }           

    return jsonResponse;
}