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


Gettting JSON data from a different website


I've asked this question already with no definite answer yet. My problem is getting JSON data from this website: http://www.ilovelimerick.ie/

this is the JSON url: http://www.ilovelimerick.ie/?json=1&count=

I need it to display in the same way as the blog reader app.

What I've learned so far is that it seems to be from a 'NegativeArraySizeException' error because its printing out a value of -1 in the Log Cat and also 'contentLength' in getBlogPostsTask class which is printing out -1 too.

But I'm still not overly sure. I think it could also be a conflict of using 'KEY_AUTHOR' because that string does not exist in the JSON data from the website I'm trying to change to. I've tried to change KEY_AUTHOR to KEY_DATE because a 'date' is used. But I still can't pull the data.

Really would appreciate some help as I've been stuck for awhile now!

Hey Neil,

A snippet from your code where you are actually parsing the JSON data would help Treehouse users like me give you a concrete solution for your problem. Since the URL is working fine without any authentication issues, the error is most probably in the part where you are extracting the JSONArray from the JSON response data you are getting after requesting the URL.

8 Answers

I think I'm having the same issue as these guys, so hopefully their solution will work out!


hopefully others may see this, as I think it could be right! fingers crossed...

Hey Devanshu! sorry here is my Main Activity

```package com.neils.blogreader;

import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap;

import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;

import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast;

public class MainListActivity extends ListActivity {

public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;

private final String KEY_TITLE = "title";
private final String KEY_AUTHOR = "author";

protected void onCreate(Bundle savedInstanceState) {

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);

    if(NetworkIsAvailable())    {
        GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
    else {
        Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();

    //String message = getString(R.string.no_items);
    //Toast.makeText(this, message, Toast.LENGTH_LONG).show();


protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    try {
    JSONArray jsonPosts = mBlogData.getJSONArray("posts");
    JSONObject jsonPost = jsonPosts.getJSONObject(position);
    String blogUrl = jsonPost.getString("url");

    Intent intent = new Intent(this,BlogWebViewActivity.class);
    catch (JSONException e) {

private void logException(Exception e) {
    Log.e(TAG, "Exception caught!", e);

private boolean NetworkIsAvailable() {
    ConnectivityManager manager = (ConnectivityManager) 
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if(networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    return isAvailable;

public void handleBlogResponse() {
    if (mBlogData == null) {
    else {
        try {
            JSONArray jsonPosts = mBlogData.getJSONArray("posts");
            ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
            for (int i = 0; i < jsonPosts.length(); i++) {
                JSONObject post = jsonPosts.getJSONObject(i);
                String title = post.getString(KEY_TITLE);
                title = Html.fromHtml(title).toString();
                String author = post.getString(KEY_AUTHOR);
                author = Html.fromHtml(author).toString();

                HashMap<String, String> blogPost = new HashMap<String, String>();
                blogPost.put(KEY_TITLE, title);
                blogPost.put(KEY_AUTHOR, author);

            String[] keys = { KEY_TITLE, KEY_AUTHOR };
            int[] ids = { android.R.id.text1, android.R.id.text2 };
            SimpleAdapter adapter = new SimpleAdapter(this, blogPosts, android.R.layout.simple_list_item_2, keys, ids);
        } catch (JSONException e) {


private void updateDisplayForError() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);    
    builder.setPositiveButton(android.R.string.ok, null);
    AlertDialog dialog = builder.create();

    TextView emptyTextView = (TextView) getListView().getEmptyView();

private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject> {

    protected JSONObject doInBackground(Object... arg0) {
           int responseCode = -1;
           JSONObject jsonResponse = null;
                URL blogFeedUrl = new URL("http://www.ilovelimerick.ie/?json=1&count=" + NUMBER_OF_POSTS);
                HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();

                responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    Reader reader = new InputStreamReader(inputStream);
                    int contentLength = connection.getContentLength();
                    char [] charArray = new char[contentLength];
                    String responseData = new String(charArray);

                    jsonResponse = new JSONObject(responseData);
                else {
                Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
            catch (MalformedURLException e) {
            catch (IOException e) {
            catch (Exception e) {

           return jsonResponse;

    protected void onPostExecute(JSONObject result) {
        mBlogData = result;



It's just the sample code from the BlogReader app but with the url I'm trying to get data from. I didn't change the' KEY_AUTHOR' section because as I said, I'm not sure if that is the problem. Thank you!

Hi Neal,

The "getContentLength()" method returns the content length in bytes specified by the response header field content-length or -1 if this field is not set. In this case, the connection response code is OK (200), therefore the only conclusion to draw here is that the content-length header field is not set on the HTTP response triggered by the URL you are using. Although, should you get past this, the KEY_AUTHOR variable also would need to be changed to something the JSON response contains, like the 'date' key you mentioned, however, it is not the primary cause here.

Ok cool! so how would I go about changing it to the correct content length header?

The server API needs to do this. The content-length field must be set at their end. You need to find out a method to calculate the contentLength without the getContentLength() method. I researched a bit, but found nothing useful to this end, since we need it to calculate the size of the char Array we want to write the response into.

So we need to find a method to calculate the content length without using getContentLength()? A different method?

A different method is needed, but I am not sure if it would be available within the android sdk or java. Try going for something like sizeof() .

This could also be one of the problems.

I see that the URL you are using might have content which is buffering (like videos/ large images)

I think you could be right because there is a lot of videos and pictures on the site!

ok cool, I'm not really sure on how to go about this as I did not create the site! where would I place sizeof()?


I have a question about how to get the Json url. I was wondering how you went from http://www.ilovelimerick.ie/

to the json url: http://www.ilovelimerick.ie/?json=1&count=