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!
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
Ishan Vyas
30,284 PointsBlog Reader app is not working and showing anything in the device .
package com.aspricot.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";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_list);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
if(isNetworkAvailabel()) {
mProgressBar.setVisibility(View.VISIBLE);
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();
}
Toast.makeText(this, "network is unavailable", Toast.LENGTH_LONG).show();
//Toast.makeText(this , message , Toast.LENGTH_LONG ).show();
}
@Override
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);
intent.setData(Uri.parse(blogUrl));
startActivity(intent);
} catch (JSONException e) {
logException(e);
}
}
private void logException(Exception e) {
Log.e(TAG , "Exception Caught!" , e);
}
private boolean isNetworkAvailabel() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if(mBlogData == null){
updateDisplayForError();
}
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(title).toString();
HashMap<String , String> blogPost = new HashMap<String,String>();
blogPost.put(KEY_TITLE ,title);
blogPost.put(KEY_AUTHOR, author);
blogPosts.add(blogPost);
}
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);
setListAdapter(adapter);
}
catch (JSONException e) {
Log.e(TAG , "Exception Caught:" , e);
}
}
}
private void updateDisplayForError() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.error_title));
builder.setMessage(getString(R.string.error_message));
builder.setPositiveButton(android.R.string.ok , null);
AlertDialog dialog = builder.create();
dialog.show();
TextView emptyTextView = (TextView) getListView().getEmptyView();
emptyTextView.setText(getString(R.string.no_items));
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject> {
@Override
protected JSONObject doInBackground(Object... arg0) {
int responseCode = -1;
JSONObject jsonResponse = null;
try {
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=20" + Number_Of_Posts);
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);
jsonResponse = new JSONObject(responseData);
}
else{ Log.i(TAG , "Unsuccessful http Code:" + responseCode);
}
}
catch(MalformedURLException e) {
logException(e);
}
catch(IOException e) {
logException(e);
}
catch(Exception e) {
logException(e);
}
return jsonResponse;
}
}
protected void onPostExecute(JSONObject result){
mBlogData = result;
}
}
Let me know the mistake if any.
2 Answers

Ben Jakuben
Treehouse TeacherCheck out this line of code:
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=20" + Number_Of_Posts);
You are concatenating "20" from Number_Of_Posts at the end of the URL, which means you end up requesting 2020 blog post summaries. That many summaries is either taking too long to generate on the backend or causing an error. Just delete the "20" in the URL string and you should be good:
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + Number_Of_Posts);

Adedara Olanrewaju
398 PointsHere is my code Mr Ben Jakuben...But I'm not getting any result
package com.example.user.blogreader;
import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.app.ListActivity; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast;
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
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.Objects;
public class MainListActivity extends ListActivity {
protected String[] mBlogPostTitles;
public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_list);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
if (isNetworkAvailable()) {
mProgressBar.setVisibility(View.VISIBLE);
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();
}
else{
Toast.makeText(this, "Network is Unavailable", Toast.LENGTH_LONG).show();
}
}
public 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.menu_main_list, menu);
return true;
}
private void updateList() {
mProgressBar.setVisibility(View.INVISIBLE);
if (mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.title));
builder.setMessage(getString(R.string.error_message));
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
TextView emptyTextView = (TextView) getListView().getEmptyView();
emptyTextView.setText(getString(R.string.no_items));
}
else{
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i=0;i<jsonPosts.length();i++) {
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mBlogPostTitles);
setListAdapter(adapter);
} catch (JSONException e) {
Log.e(TAG,"Exception caught!", e);
}
}
}
@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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class GetBlogPostsTask extends AsyncTask<Object,Void,JSONObject>{
@Override
protected JSONObject doInBackground(Object... arg0){
int responseCode = -1;
JSONObject jsonResponse = null;
try {
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
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 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
}
jsonResponse = new JSONObject(responseData);
} 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 jsonResponse;
//Toast.makeText(this,getString(R.string.no_item), Toast.LENGTH_LONG).show();
}
@Override
//A bridge between an AsyncTask nd the class using it
protected void onPostExecute(JSONObject result) {
mBlogData = result;
updateList();
}
}
}
Please Help I need to finish the tutorial ASAP