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

Blog Reader App problem... Not able to get JSON data in the log.

Hi friends... my blog reader app doesn't seem to be working properly and i am getting an IOException from the try-catch block in the 'doInBackground' method... plus the 'responseCode' is -1.

My internet connection is working properly... i have checked it many times.

Please help!

Below is my code:

package com.divyansh.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 org.json.JSONArray;
import org.json.JSONException;
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.view.MenuItem;
import android.widget.Toast;

public class MainListActivity extends ListActivity {

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

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

        if(isNetworkAvailable()){
            GetBlogPostsTask getBlogPostTask = new GetBlogPostsTask();
            getBlogPostTask.execute();


        }else{
                    Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
                }




        //  Toast.makeText(this, message, 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;
    }

    public void updateList() {
        if(mBlogData ==  null){
        // TODO: Handle error 
        }else{
            try {
                Log.d(TAG,mBlogData.toString(2));
            } catch (JSONException e) {
                Log.d(TAG,"Exception caught!",e);
            }
        }
    }

    @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, 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();
                Log.i(TAG, "Response is" + responseCode);
                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 Response Code: " + responseCode);
                }               
            }
            catch(MalformedURLException e){
                Log.e(TAG,"URL Exception caught");
            }
            catch(IOException e){
                Log.e(TAG,"IO Exception caught");
            }           
            catch(Exception e){
                Log.e(TAG,"Exception caught");
            }

            Log.i(TAG,"Response" + responseCode);
            return jsonResponse;
        }

        @Override
        protected void onPostExecute(JSONObject result){
            mBlogData = result;
            updateList();
        }
    }




     @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);
        }

    }

I'm having the same problem, but mine isn't solved when I restart--and I restarted everything more than once. I get the same I/O exception and response code every time. My code looks to be exactly the same as yours, as far as I can tell.

I'm working from a public computer. Could that possibly have anything to do with it? The internet connection is very fast and has never given me trouble in the past.

I think its the order in which you are opening your eclipse and emulator... for me it was the same problem... Marcus, open the 'eclipse' first and then the emulator after sometime...

Emulator connects with eclipse and then communicates with it... if you want to see how... just switch to logcat in eclipse immediately when you start your emulator... some messages pop up...

Hope that helps...

1 Answer

Hey it is solved... there is no error in the code... just the eclipse IDE and emulator were not coordinating well. When i restarted everything... it worked! :)

I think its the order in which you are opening your eclipse and emulator... for me it was the same problem... open the 'eclipse' first and then the emulator after sometime...