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

Constructor intent error

I'm getting this error: "The constructor Intent(NewsFragment, Class<BlogWebViewActivity>) is undefined"

for this line:

Intent intent = new Intent(this,BlogWebViewActivity.class);

any help would be appreciated!

9 Answers

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

The issue is that Fragment (the parent of NewsFragment, I'm assuming) is not a descendent of Context. This is one area where Activities and Fragments are different. We can use this to refer to the Context inside activities because the Activity base class extends the Context class.

Anyhow, a simple solution in Fragments is to use the method getActivity() instead of this when referring to the context. getActivity() gets the activity that the Fragment is currently running in, which is the appropriate context to use.

Thanks, that worked great!

I have 1 more error that I'm unsure about that I think relates to the fact I am using a fragment instead of an activity on this line:

getSystemService(Context.CONNECTIVITY_SERVICE);

The method getSystemService(String) is undefined for the type NewsFragment

Ben Jakuben
Ben Jakuben
Treehouse Teacher

That's a method from the Context class, so you'll need to call it from a Context (or subclass) object. Since getActivity() gives you an Activity object, you should be able to do this:

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

There are no errors but now the app won't run. I'm getting these messages in the log cat

02-26 19:13:08.033: E/AndroidRuntime(1280): FATAL EXCEPTION: main

02-26 19:13:08.033: E/AndroidRuntime(1280): java.lang.NullPointerException

02-26 19:13:08.033: E/AndroidRuntime(1280): at com.teamtreehouse.ribbit.NewsFragment.onCreate(NewsFragment.java:65)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.app.Fragment.performCreate(Fragment.java:1477)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:823)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:841)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.view.ViewPager.populate(ViewPager.java:1066)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.View.measure(View.java:15848)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.View.measure(View.java:15848)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)

02-26 19:13:08.033: E/AndroidRuntime(1280): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.View.measure(View.java:15848)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

02-26 19:13:08.033: E/AndroidRuntime(1280): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.View.measure(View.java:15848)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.Choreographer.doCallbacks(Choreographer.java:562)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.Choreographer.doFrame(Choreographer.java:532)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.os.Handler.handleCallback(Handler.java:730)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.os.Handler.dispatchMessage(Handler.java:92)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.os.Looper.loop(Looper.java:137)

02-26 19:13:08.033: E/AndroidRuntime(1280): at android.app.ActivityThread.main(ActivityThread.java:5103)

02-26 19:13:08.033: E/AndroidRuntime(1280): at java.lang.reflect.Method.invokeNative(Native Method)

02-26 19:13:08.033: E/AndroidRuntime(1280): at java.lang.reflect.Method.invoke(Method.java:525)

02-26 19:13:08.033: E/AndroidRuntime(1280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

02-26 19:13:08.033: E/AndroidRuntime(1280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

02-26 19:13:08.033: E/AndroidRuntime(1280): at dalvik.system.NativeStart.main(Native Method)

02-26 19:19:37.457: D/dalvikvm(1488): GC_FOR_ALLOC freed 182K, 25% free 2784K/3680K, paused 3ms, total 3ms

02-26 19:19:37.461: D/dalvikvm(1488): GC_FOR_ALLOC freed 100K, 26% free 3002K/4004K, paused 2ms, total 2ms

02-26 19:19:37.469: I/dalvikvm-heap(1488): Grow heap (frag case) to 4.700MB for 1127532-byte allocation

02-26 19:19:37.489: D/dalvikvm(1488): GC_FOR_ALLOC freed <1K, 20% free 4103K/5108K, paused 21ms, total 21ms

02-26 19:19:37.501: D/dalvikvm(1488): GC_FOR_ALLOC freed <1K, 20% free 4103K/5108K, paused 7ms, total 7ms

02-26 19:19:37.509: I/dalvikvm-heap(1488): Grow heap (frag case) to 7.119MB for 2536932-byte allocation

02-26 19:19:37.533: D/dalvikvm(1488): GC_FOR_ALLOC freed 0K, 14% free 6580K/7588K, paused 3ms, total 3ms

02-26 19:19:37.545: I/MainActivity(1488): neil

02-26 19:19:37.581: D/AndroidRuntime(1488): Shutting down VM

02-26 19:19:37.581: W/dalvikvm(1488): threadid=1: thread exiting with uncaught exception (group=0xa4baa648)

02-26 19:19:37.581: E/AndroidRuntime(1488): FATAL EXCEPTION: main

02-26 19:19:37.581: E/AndroidRuntime(1488): java.lang.NullPointerException

02-26 19:19:37.581: E/AndroidRuntime(1488): at com.teamtreehouse.ribbit.NewsFragment.onCreate(NewsFragment.java:65)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.app.Fragment.performCreate(Fragment.java:1477)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:823)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:841)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.view.ViewPager.populate(ViewPager.java:1066)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.view.ViewPager.populate(ViewPager.java:914)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.View.measure(View.java:15848)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.View.measure(View.java:15848)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)

02-26 19:19:37.581: E/AndroidRuntime(1488): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.View.measure(View.java:15848)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)

02-26 19:19:37.581: E/AndroidRuntime(1488): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.View.measure(View.java:15848)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.Choreographer.doCallbacks(Choreographer.java:562)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.Choreographer.doFrame(Choreographer.java:532)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.os.Handler.handleCallback(Handler.java:730)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.os.Handler.dispatchMessage(Handler.java:92)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.os.Looper.loop(Looper.java:137)

02-26 19:19:37.581: E/AndroidRuntime(1488): at android.app.ActivityThread.main(ActivityThread.java:5103)

02-26 19:19:37.581: E/AndroidRuntime(1488): at java.lang.reflect.Method.invokeNative(Native Method)

02-26 19:19:37.581: E/AndroidRuntime(1488): at java.lang.reflect.Method.invoke(Method.java:525)

02-26 19:19:37.581: E/AndroidRuntime(1488): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

02-26 19:19:37.581: E/AndroidRuntime(1488): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

02-26 19:19:37.581: E/AndroidRuntime(1488): at dalvik.system.NativeStart.main(Native Method)

Ben Jakuben
Ben Jakuben
Treehouse Teacher

Want to paste in your code? We can try to track down that NullPointerException :)

02-26 19:13:08.033: E/AndroidRuntime(1280): at com.teamtreehouse.ribbit.NewsFragment.onCreate(NewsFragment.java:65)

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
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.support.v4.app.ListFragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class NewsFragment extends ListFragment{

    public static final int NUMBER_OF_POSTS = 20;
    public static final String TAG = NewsFragment.class.getSimpleName();
    protected JSONObject mBlogData;
    protected ProgressBar mProgressBar;

    private final String KEY_TITLE = "title";
    private final String KEY_DATE = "date";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_news_list,
                container, false);
        mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBar1);

        return rootView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(NetworkIsAvailable())    {
            mProgressBar.setVisibility(View.VISIBLE);
            GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
            getBlogPostsTask.execute();
        }
        else {
            Toast.makeText(getActivity(), "Network is unavailable!", Toast.LENGTH_LONG).show();
        }

        //String message = getString(R.string.no_items);
        //Toast.makeText(this, message, Toast.LENGTH_LONG).show();

    }

    @Override
    public 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(getActivity(),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 NetworkIsAvailable() {
        ConnectivityManager manager = (ConnectivityManager) 
        getActivity().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 date = post.getString(KEY_DATE);
                    date = Html.fromHtml(date).toString();

                    HashMap<String, String> blogPost = new HashMap<String, String>();
                    blogPost.put(KEY_TITLE, title);
                    blogPost.put(KEY_DATE, date);

                    blogPosts.add(blogPost);
                }
                String[] keys = { KEY_TITLE, KEY_DATE };
                int[] ids = { android.R.id.text1, android.R.id.text2 };
                SimpleAdapter adapter = new SimpleAdapter(getActivity(), blogPosts, android.R.layout.simple_list_item_2, keys, ids);
                setListAdapter(adapter);
            } catch (JSONException e) {
                logException(e);
            }
        }

    }


    private void updateDisplayForError() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());   
        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... params) {
            int responseCode = -1;
            JSONObject jsonResponse = null;
            StringBuilder builder = new StringBuilder();
            HttpClient client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://www.ilovelimerick.ie/?json=1&count=");

            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){
                        builder.append(line);
                    }

                    jsonResponse = new JSONObject(builder.toString());
                }
                else {
                    Log.i(TAG, String.format("Unsuccessful HTTP response code: %d", responseCode));
                }
            }
            catch (JSONException e) {
                logException(e);
            }
            catch (Exception e) {
                logException(e);
            }           

            return jsonResponse;
        }   

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

    }
}
Ben Jakuben
Ben Jakuben
Treehouse Teacher

Okay, I think I know what's going on here. Line 65 is this line:

mProgressBar.setVisibility(View.VISIBLE);

For Fragments, all code related to the layouts should be in the onCreateView() method, like you have for setting mProgressBar. onCreate() is called before onCreateView(), meaning that it's trying to call setVisibility() before mProgressBar has been set. (see the lifecycle diagram here: http://developer.android.com/guide/components/fragments.html)

Try moving all your code from onCreate() into onCreateView().

so by move do you mean swap the position of onCreate() with onCreateView() like so: it still doesn't run when I do that.

public class NewsFragment extends ListFragment{

public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = NewsFragment.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;

private final String KEY_TITLE = "title";
private final String KEY_DATE = "date";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(NetworkIsAvailable())    {
        mProgressBar.setVisibility(View.VISIBLE);
        GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
        getBlogPostsTask.execute();
    }
    else {
        Toast.makeText(getActivity(), "Network is unavailable!", Toast.LENGTH_LONG).show();
    }

    //String message = getString(R.string.no_items);
    //Toast.makeText(this, message, Toast.LENGTH_LONG).show();

}

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_news_list, container, false); mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBar1);

    return rootView;
}

@Override
public 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(getActivity(),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 NetworkIsAvailable() {
    ConnectivityManager manager = (ConnectivityManager) 
    getActivity().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 date = post.getString(KEY_DATE);
                date = Html.fromHtml(date).toString();

                HashMap<String, String> blogPost = new HashMap<String, String>();
                blogPost.put(KEY_TITLE, title);
                blogPost.put(KEY_DATE, date);

                blogPosts.add(blogPost);
            }
            String[] keys = { KEY_TITLE, KEY_DATE };
            int[] ids = { android.R.id.text1, android.R.id.text2 };
            SimpleAdapter adapter = new SimpleAdapter(getActivity(), blogPosts, android.R.layout.simple_list_item_2, keys, ids);
            setListAdapter(adapter);
        } catch (JSONException e) {
            logException(e);
        }
    }

}


private void updateDisplayForError() {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());   
    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... params) {
        int responseCode = -1;
        JSONObject jsonResponse = null;
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://www.ilovelimerick.ie/?json=1&count=");

        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){
                    builder.append(line);
                }

                jsonResponse = new JSONObject(builder.toString());
            }
            else {
                Log.i(TAG, String.format("Unsuccessful HTTP response code: %d", responseCode));
            }
        }
        catch (JSONException e) {
            logException(e);
        }
        catch (Exception e) {
            logException(e);
        }           

        return jsonResponse;
    }   

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

}

}

Ben Jakuben
Ben Jakuben
Treehouse Teacher

Ah, no. I see why you might think that, though. :) The order of the methods doesn't matter in the class itself. The order I'm referring to is how they're called by the Android system. onCreate() will always be called before onCreateView() when Android is loading a Fragment.

So you want to end up with this. You can actually get rid of the whole onCreate() method for now:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_news_list,
                container, false);
        mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBar1);

        if(NetworkIsAvailable())    {
            mProgressBar.setVisibility(View.VISIBLE);
            GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
            getBlogPostsTask.execute();
        }
        else {
            Toast.makeText(getActivity(), "Network is unavailable!", Toast.LENGTH_LONG).show();
        }

        //String message = getString(R.string.no_items);
        //Toast.makeText(this, message, Toast.LENGTH_LONG).show();

        return rootView;
    }

That worked perfectly! Thanks Ben :)

For some reason now once I click into a blog post title to try and open the post, the app crashes!

02-26 22:26:40.695: E/AndroidRuntime(1277): FATAL EXCEPTION: main

02-26 22:26:40.695: E/AndroidRuntime(1277): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.teamtreehouse.ribbit/com.teamtreehouse.ribbit.BlogWebViewActivity}; have you declared this activity in your AndroidManifest.xml?

02-26 22:26:40.695: E/AndroidRuntime(1277): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.app.Activity.startActivityForResult(Activity.java:3390) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.app.Activity.startActivityForResult(Activity.java:3351) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.support.v4.app.Fragment.startActivity(Fragment.java:878) 02-26 22:26:40.695: E/AndroidRuntime(1277): at com.teamtreehouse.ribbit.NewsFragment.onListItemClick(NewsFragment.java:83) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.widget.AdapterView.performItemClick(AdapterView.java:298) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.widget.AbsListView.performItemClick(AbsListView.java:1100) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.widget.AbsListView$1.run(AbsListView.java:3463) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.os.Handler.handleCallback(Handler.java:730) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.os.Handler.dispatchMessage(Handler.java:92) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.os.Looper.loop(Looper.java:137) 02-26 22:26:40.695: E/AndroidRuntime(1277): at android.app.ActivityThread.main(ActivityThread.java:5103) 02-26 22:26:40.695: E/AndroidRuntime(1277): at java.lang.reflect.Method.invokeNative(Native Method) 02-26 22:26:40.695: E/AndroidRuntime(1277): at java.lang.reflect.Method.invoke(Method.java:525) 02-26 22:26:40.695: E/AndroidRuntime(1277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 02-26 22:26:40.695: E/AndroidRuntime(1277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 02-26 22:26:40.695: E/AndroidRuntime(1277): at dalvik.system.NativeStart.main(Native Method)

it asks have you declared this activity in your AndroidManifest.xml? which I have...

Ben Jakuben
Ben Jakuben
Treehouse Teacher

This thread is getting a little unwieldy...would you mind pasting this into a new Forum post so we can separate the issues? :) I'll come back and delete these comments if you do that.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.teamtreehouse.ribbit" android:versionCode="1" android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" android:name="RibbitApplication">
    <activity
        android:name="com.teamtreehouse.ribbit.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.teamtreehouse.ribbit.LoginActivity"
        android:label="@string/title_activity_login"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.teamtreehouse.ribbit.SignUpActivity"
        android:label="@string/title_activity_sign_up"
        android:parentActivityName="com.teamtreehouse.ribbit.LoginActivity"
        android:screenOrientation="portrait" >
    </activity>
    <activity
        android:name="com.neils.blogreader.BlogWebViewActivity"
        android:label="@string/title_activity_blog_web_view" >
    </activity>
</application>

</manifest>