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 trialTimothy Boland
18,237 PointsGoogle JSON API - Not sure how to get the results objects
Im trying to do the Google JSON API extra credit...but im stuck on handling the json response....unlike the Treehouse json...the results objects are nested within the responseData object....ive tried doing getJSONArray on both results and responseData...but i get errors for both:
Here is some of my code:
public void handleSearchResponse() {
//mProgressBar.setVisibility(View.INVISIBLE);
if (mSearchData == null) {
updateDisplayForError();
} else {
try {
JSONArray jsonResults = mSearchData.getJSONArray("responseData");
ArrayList<HashMap<String, String>> searchResults =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonResults.length(); i++) {
JSONObject result = jsonResults.getJSONObject(i);
String title = result.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
Log.v(TAG, title);
When i try getJSONArray("responseData")
I get the following error:
responseData of type org.json.JSONObject cannot be converted to JSONArray
When I try getJSONArray("results")
I get the following error:
Exception Caught!
org.json.JSONException: No value for results
1 Answer
Timothy Boland
18,237 PointsI found the answer from this tutorial:
http://android-er.blogspot.com/2012/09/implement-google-search-json-for-android.html
I had to load the jsonResponse into a JSONObject first to fetch the responseData object, then use that responseData object to access the results array....like so:
public void handleSearchResponse() {
//mProgressBar.setVisibility(View.INVISIBLE);
if (mSearchData == null) {
updateDisplayForError();
} else {
try {
JSONObject jsonObjectResponseData = mSearchData.getJSONObject("responseData");
JSONArray jsonResults = jsonObjectResponseData.getJSONArray("results");
ArrayList<HashMap<String, String>> searchResults =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonResults.length(); i++) {
JSONObject result = jsonResults.getJSONObject(i);
String title = result.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
Log.v(TAG, title);