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

Richard Luick
Richard Luick
10,955 Points

JSON Google Search Extra Credit

Hello everyone, after watching the lesson "Getting Data from the Web" in the BLog Reader project I decided to take a stab at the EC asking to get JSON data from a google search. I am currently just attempting to log the results to the Console but I am encountering an error I cannot seem to debug. I basically started with a copy of the blogreader project, and after doing some research I came up with the following modified code for the google api.

package com.example.googlereaderec;

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 org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainListActivity extends ListActivity {

    protected String[] mBlogPostTitles;
    public static final int NUMBER_OF_POSTS = 20;
    public static final String TAG = MainListActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_list);

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

        //Toast.makeText(this, getString(R.string.no_items), Toast.LENGTH_LONG).show();
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_list, menu);
        return true;
    }

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

        @Override
        protected String doInBackground(Object... params) {
            int responseCode = -1;

            try {
                URL blogFeedUrl = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=JSON");
                HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
                connection.connect();

                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];
                    reader.read(charArray);
                    String responseData = new String(charArray);

                    JSONObject jsonResponse = new JSONObject(responseData);
                    JSONObject jsonResponseData = jsonResponse.getJSONObject("responseData");
                    JSONArray jsonResults = jsonResponseData.getJSONArray("results");                   

                    for(int i = 0; i < jsonResults.length(); i++) {
                        JSONObject jsonPost = jsonResults.getJSONObject(i);
                        String url = jsonPost.getString("url");
                        Log.v(TAG, "Result " + i + ": " + url);
                    }
                }
                else {
                    Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
                }   
            } 
            catch(MalformedURLException e) {
                Log.e(TAG, "Exception caught: ", e);
            } 
            catch(IOException e) {
                Log.e(TAG, "Exception caught: ", e);
            }
            catch(Exception e) {
                Log.e(TAG, "Exception caught: ", e);
            }

            return "Code: " + responseCode;
        }

    }

}

Specifically, this segment

protected String doInBackground(Object... params) {
            int responseCode = -1;

            try {
                URL blogFeedUrl = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=JSON");
                HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
                connection.connect();

                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];
                    reader.read(charArray);
                    String responseData = new String(charArray);

                    JSONObject jsonResponse = new JSONObject(responseData);
                    JSONObject jsonResponseData = jsonResponse.getJSONObject("responseData");
                    JSONArray jsonResults = jsonResponseData.getJSONArray("results");                   

                    for(int i = 0; i < jsonResults.length(); i++) {
                        JSONObject jsonPost = jsonResults.getJSONObject(i);
                        String url = jsonPost.getString("url");
                        Log.v(TAG, "Result " + i + ": " + url);
                    }
                }
                else {
                    Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
                }   
            } 
            catch(MalformedURLException e) {
                Log.e(TAG, "Exception caught: ", e);
            } 
            catch(IOException e) {
                Log.e(TAG, "Exception caught: ", e);
            }
            catch(Exception e) {
                Log.e(TAG, "Exception caught: ", e);
            }

            return "Code: " + responseCode;
        }

My logcat seems to indicate that an exception is being thrown in the try/catch block but I don't understand why. Any help is appreciated. Thanks.

Richard Luick
Richard Luick
10,955 Points

Heres the logcat sorry

08-07 20:53:06.523: E/MainListActivity(8849): Exception caught: 
08-07 20:53:06.523: E/MainListActivity(8849): java.lang.NegativeArraySizeException: -1
08-07 20:53:06.523: E/MainListActivity(8849):   at com.example.googlereaderec.MainListActivity$GetBlogPostsTask.doInBackground(MainListActivity.java:80)
08-07 20:53:06.523: E/MainListActivity(8849):   at com.example.googlereaderec.MainListActivity$GetBlogPostsTask.doInBackground(MainListActivity.java:1)
08-07 20:53:06.523: E/MainListActivity(8849):   at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-07 20:53:06.523: E/MainListActivity(8849):   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-07 20:53:06.523: E/MainListActivity(8849):   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-07 20:53:06.523: E/MainListActivity(8849):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-07 20:53:06.523: E/MainListActivity(8849):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-07 20:53:06.523: E/MainListActivity(8849):   at java.lang.Thread.run(Thread.java:841)

3 Answers

Joe Brown
Joe Brown
21,465 Points

Heres the link to solve your problem, read thru that, there is a simpler(less code) solution that is posted by someone in there also I think other than the first post that Ben puts up but either way works.... https://teamtreehouse.com/forum/trying-to-retrieve-data-from-my-own-blog-help

Richard Luick
Richard Luick
10,955 Points

Hey thank you very much for pointing me in the right direction. I replaced this:

int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);

with this

int nextCharacter; // read() returns an int, we cast it to char later
String responseData = "";
while(true){ // Infinite loop, can only be stopped by a "break" statement
    nextCharacter = reader.read(); // read() without parameters returns one character
    if(nextCharacter == -1) // A return value of -1 means that we reached the end
        break;
    responseData += (char) nextCharacter; // The += operator appends the character to the end of the string
}

And now everything is logging correctly!

Joe Brown
Joe Brown
21,465 Points

Your issue is probably in the line where you have "int contentLength". These is fixed in another thread, im sorry i dont remember where it is located to give you the link but it is here on the forum.. basically Ben set the Blog Reader project up knowing the content length of the returned info or something like that, in the extra credit thought(and any other use you will probably try), you cant set content length in that way. Its a simple fix, just search the forum here or some one may pop in with the link for you. I will look for it myself for you also

Joe Brown
Joe Brown
21,465 Points

Oh I just saw your logcat post there. Yea your problem is the content length, thats why your getting -1 as a value, thats an error code of some sort