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
David Hope
19,876 PointsNo value found for JSON Array
Hello everyone, I'm going back through the Build a Simple Blog Reader project using my favorite sports blog and the API service kimono to get JSON data for it. I'm following the format Mr. Jakuben used here in the first comment https://teamtreehouse.com/forum/trying-to-retrieve-data-from-my-own-blog-help Every time I try to enter the JSON Array for it, using getJSONArray() the array fails to load when running the program with an error saying "No value for collection" , collection being the name of the JSON Array. The JSON Array itself is wrapped inside a JSON Object. Here is the API I'm using: https://www.kimonolabs.com/api/blk9qa9y?apikey=k0m9jpyIsYc3Jstozmtu4Xd5G7XdToRw
Also included below is my code for this project. What is needed to fix this issue? Thank you all in advance!
public class MainBlogPostListActivity extends Activity {
protected String[] mBlogPostHeadlines;
protected static final String TAG = MainBlogPostListActivity.class.getSimpleName();
protected JSONObject mBlogData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_blog_post_list);
if ( isNetworkAvailable() ) {
getBlogPostTask getBlogPostsTask = new getBlogPostTask();
getBlogPostsTask.execute();
}
else {
AlertDialog.Builder networkDownBuilder = new AlertDialog.Builder(MainBlogPostListActivity.this);
networkDownBuilder.setMessage(R.string.network_connection_failed_message)
.setTitle(R.string.network_connection_failed_title)
.setNegativeButton(android.R.string.cancel, null);
AlertDialog connectionDown = networkDownBuilder.create();
connectionDown.show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean networkAvailability = false;
if ( networkInfo !=null && networkInfo.isConnected() ) {
networkAvailability = true;
}
return networkAvailability;
}
private void updateList() {
if (mBlogData == null) {
// TODO: Handle Error
}
else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("collection");
mBlogPostHeadlines = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
String href = post.getString("href");
href = Html.fromHtml(href).toString();
mBlogPostHeadlines[i] = href;
}
ListView listView = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mBlogPostHeadlines);
listView.setAdapter(adapter);
}
catch (JSONException e) {
Log.e(TAG, "Exception Caught: ", e);
}
}
}
private class getBlogPostTask extends AsyncTask<Object, Void, JSONObject> {
@Override
protected JSONObject doInBackground(Object... params) {
int responseCode = -1;
JSONObject jsonResponse = null;
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://www.kimonolabs.com/api/blk9qa9y?apikey=k0m9jpyIsYc3Jstozmtu4Xd5G7XdToRw");
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) {
stringBuilder.append(line);
}
jsonResponse = new JSONObject(stringBuilder.toString());
} else {
Log.i(TAG, "Unsuccessful Response Code: " + responseCode);
}
} catch (JSONException e) {
Log.e(TAG, "JSON Exception caught: ", e);
} 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 jsonResponse;
}
@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
@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_blog_post_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
4 Answers
Ben Jakuben
Treehouse TeacherHi David,
You'll need to rework how you are parsing the JSON data in your updateList() method. You first need to get the response JSON object from the data before you try to get the collection array.
Check out this untested code that might help you along the way. It will probably help you to log the different JSON data as you work through each step.
JSONObject jsonResponse = mBlogData.getJSONObject("results");
JSONArray jsonPosts = jsonResponse.getJSONArray("collection");
mBlogPostHeadlines = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(
String href = post.getString("href");
href = Html.fromHtml(href).toString();
mBlogPostHeadlines[i] = href;
}
Derrick Shepherd
4,861 PointsLol, I see, no problem, hope you found the solution, best wishes in your studies...
David Hope
19,876 PointsI haven't found it yet, but there's bound to be one somewhere. Thanks and good luck to you as well Derrick!
Derrick Shepherd
4,861 PointsHi Davaid,
I found two errors in your code,
Remove the "less than" symbol from the line below.
JSONArray jsonPosts = < mBlogData.getJSONArray("collection");
Also remove the one next to "Void" on this line of code seen below.
private class getBlogPostTask extends AsyncTask<Object, <Void, JSONObject> {
Recheck the rest of your code just to make sure there are no other errors, hope this helps.
Derrick Shepherd
4,861 PointsDavid, sorry (typo)
David Hope
19,876 PointsHello Derrick, I appreciate your help. Those typos aren't in my code, but from trying use the syntax here on the forum to highlight it as code. The angle brackets and ` characters on the sides are from that as well. Sorry about the confusion Derrick.
Derrick Shepherd
4,861 PointsThanks
David Hope
19,876 PointsDavid Hope
19,876 PointsThank you Mr. Jakuben for the detailed explanation and code example!
Things are now working thanks to your help :)