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 Build a Blog Reader Android App Using Intents to Display and Share Posts Opening a Webpage in the Browser

blogreader has stoped

Hi, some times i run the blog reader it simply crashes showing the typical messge the application has stopped. Here's the log

10-06 10:20:07.876 10561-10561/cursosalamedida.gecoders.blogreader W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41915898) 10-06 10:20:07.876 10561-10561/cursosalamedida.gecoders.blogreader E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException at cursosalamedida.gecoders.blogreader.MainListActivity.updateDisplayForError(MainListActivity.java:147) at cursosalamedida.gecoders.blogreader.MainListActivity.handleBlogResponse(MainListActivity.java:107) at cursosalamedida.gecoders.blogreader.MainListActivity.access$200(MainListActivity.java:40) at cursosalamedida.gecoders.blogreader.MainListActivity$GetBlogPostsTask.onPostExecute(MainListActivity.java:199) at cursosalamedida.gecoders.blogreader.MainListActivity$GetBlogPostsTask.onPostExecute(MainListActivity.java:151) at android.os.AsyncTask.finish(AsyncTask.java:631) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5450) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) at dalvik.system.NativeStart.main(Native Method)

Boris Pruissen
Boris Pruissen
1,401 Points

Hi luis, you propbably should add an extra catch block in your asynctask for retrieving data, catch(Exception e) {}, it also could be that your asynctask returns nothing (null in this case) and the handleBlogResponse tries to add this to your listAdapter, which is not possible...

Boris. I forgot to post my code. I have tree exceptions covered MalfmedUrlException, IOException and Exception. So thats no the problem

Off course, yesterday i didn't because i was in the smartphone. Here is the MainListActivity. I know the problem is here because it exist before the problem take place the first time.

package cursosalamedida.gecoders.blogreader;

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.Menu; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; 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.ArrayList; import java.util.HashMap;

public class MainListActivity extends ListActivity { //protected String[] mBlogPostTitles; public static final int NUMBER_OF_POST=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_list); mProgressBar=(ProgressBar)findViewById(R.id.progressBar); if(isNetworkAvalaible()){ mProgressBar.setVisibility(View.VISIBLE); GetBlogPostsTask getBlogPostsTask=new GetBlogPostsTask(); getBlogPostsTask.execute(); }else{ Toast.makeText(this,"Network is unavailable",Toast.LENGTH_SHORT).show(); } /Resources resources=getResources(); mBlogPostTitles =resources.getStringArray(R.array.android_names); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mBlogPostTitles); setListAdapter(adapter);/ //Toast.makeText(this,getString(R.string.no_items),Toast.LENGTH_SHORT).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(Intent.ACTION_VIEW);
        Intent  intent=new Intent(this,BlogViewActivity.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 isNetworkAvalaible() {
    boolean isAvailable=false;
    ConnectivityManager manager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo=manager.getActiveNetworkInfo();
    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.list, menu);
    return true;
}
private 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>>();

            //mBlogPostTitles=new String[jsonPosts.length()];
            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(author).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);
            //ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mBlogPostTitles);
            setListAdapter(adapter);
            //Log.d(TAG,mBlogData.toString(2));
        } catch (JSONException e) {
            logException(e);
        }
    }
}

private void updateDisplayForError() {
    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(R.string.no_items);
}


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

    @Override
    protected JSONObject doInBackground(Object... strings) {
        int responsecode=-1;
        JSONObject jsonResponse=null;
        try {
            URL blogFeedURL = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count="+NUMBER_OF_POST);
            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);
               /* String status=jsonResponse.getString("status");
                JSONArray jsonPosts=jsonResponse.getJSONArray("posts");
                for(int i=0;i<jsonPosts.length();i++){
                    JSONObject jsonPost=jsonPosts.getJSONObject(i);
                    String title=jsonPost.getString("title");

                }
                //Log.v(TAG,responseData);*/
            }else {
                Log.i(TAG, "Unsuccessful responseCode: " + responsecode);
            }
        }catch (MalformedURLException e){
            logException(e);
        }catch (IOException e){
            logException(e);
        }catch(Exception e){
            logException(e);
        }
        return jsonResponse;
     }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

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

}

2 Answers

The problem seems to be the retriving JSON from the treehouse blog. some times the log cat reports some errors related.

Boris Pruissen
Boris Pruissen
1,401 Points

Could you post the code then? You have an nullpointer Exception, which mains somewhere you didn't check for an null value