Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

alex gwartney
alex gwartney
8,849 Points

Null pointer exception error?

So im getting the error java.lang.NullPointerException at android.support.v7.widget.RecyclerView.onMeasure But i have researched it and it has to do with setting the the layout manager for recycle view which from what i understand i did. So could some one take a look at my code and see what im doing wrong.

public class MainActivity extends ActionBarActivity {



    public String url = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
    public static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;

    content[] mDataset;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        if(isNetworkAvailable()) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            getCurrentDetails(jsonData);


                            mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
                            LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
                            mRecyclerView.setLayoutManager(layoutManager);

                            mAdapter = new MyAdapter(mDataset);
                            mRecyclerView.setAdapter(mAdapter);


                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    } catch (JSONException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                }
            });
        }


    }




    private content[] getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);

        JSONArray data = forecast.getJSONArray("posts");

         mDataset = new content[data.length()];

        for (int i = 0; i < data.length(); i++) {

            JSONObject jsonDay = data.getJSONObject(i);
            content day = new content();

            day.setId(jsonDay.getInt("id"));
            day.setUrl(jsonDay.getString("url"));
            day.setTitle(jsonDay.getString("title"));
            day.setDate(jsonDay.getString("date"));
            day.setAuthor(jsonDay.getString("author"));
            day.setThumbnail(jsonDay.getString("thumbnail"));
            mDataset[i] = day;
        }


        return mDataset;

    }


    // This will check if there is a net work conection
    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;
    }







}

Hi Alex,

Can you post the Logcat contents too, please?

Thanks,

Steve.

alex gwartney
alex gwartney
8,849 Points

do you want the full error that is showing up in log cat? or are you meaning all the other logs that im running for json?

alex gwartney
alex gwartney
8,849 Points

Here is the full log cat error

06-26 11:39:50.762 32650-32650/alexgwartney.treehouseblogreader E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: alexgwartney.treehouseblogreader, PID: 32650 java.lang.NullPointerException at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:1764) at android.view.View.measure(View.java:16849) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:824) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:500) at android.view.View.measure(View.java:16849) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378) at android.widget.FrameLayout.onMeasure(FrameLayout.java:340) at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124) at android.view.View.measure(View.java:16849) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378) at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:444) at android.view.View.measure(View.java:16849) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378) at android.widget.FrameLayout.onMeasure(FrameLayout.java:340) at android.view.View.measure(View.java:16849) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621) at android.widget.LinearLayout.measureVertical(LinearLayout.java:742) at android.widget.LinearLayout.onMeasure(LinearLayout.java:607) at android.view.View.measure(View.java:16849) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378) at android.widget.FrameLayout.onMeasure(FrameLayout.java:340) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2368) at android.view.View.measure(View.java:16849) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1334) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1532) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1211) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6282) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788) at android.view.Choreographer.doCallbacks(Choreographer.java:591) at android.view.Choreographer.doFrame(Choreographer.java:560) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5323) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641) at dalvik.system.NativeStart.main(Native Method)

alex gwartney
alex gwartney
8,849 Points

also the json response is working

Seems to be a messy issue - well over my head!

Stack Overflow has a lot of suggestions, though.

Here's one: http://stackoverflow.com/questions/26737113/java-lang-nullpointerexception-at-android-support-v7-widget-recyclerview-onmeasu

Sorry I can't be any more precise. One alternative would be to upload your project to Github or BitBucket - I can then generate the issue here too and work towards fixing it.

Steve.

alex gwartney
alex gwartney
8,849 Points

yea im going to have to upload it for you because i have read through that and others and thats why im posting on here.

Cool - chuck it in a repository and look me up on either site. I'm OnlySteveH on both.

I'll pull the code down and replicate the issue here and see if I can solve it !!

alex gwartney
alex gwartney
8,849 Points

ok Steve i just followed you on there the code is on github my name on there is gwartney21 also here is a link to it here https://github.com/gwartney21/android-blog-reader

Is this project in Android Studio using Gradle? I'm getting a raft of issues trying to import it.

alex gwartney
alex gwartney
8,849 Points

let me know if you are still having issues downloading it?

I can't get it working here - my Android Studio isn't recognising something so the Manifest isn't working and it won't compile.

I'll keep trying!

alex gwartney
alex gwartney
8,849 Points

if you would like i can send the project in a zip folder through email if you message me on github or through skype or something

alex gwartney
alex gwartney
8,849 Points

also i appreciate the help

6 Answers

Jon Kussmann
PLUS
Jon Kussmann
Courses Plus Student 7,254 Points

This should work. I haven't checked if I'm missing a bracket, etc. Let me know if it doesn't work.

public class MainActivity extends ActionBarActivity {
    public String url = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
    public static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;

    content[] mDataset;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setLayoutManager(layoutManager);


        if(isNetworkAvailable()) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            getCurrentDetails(jsonData);

                            runOnUiThread(new Runnable() {
                                  @Override
                                  public void run() {
                                         mAdapter = new MyAdapter(mDataset);
                                         mRecyclerView.setAdapter(mAdapter);
                                  });
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    } catch (JSONException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                }
            });
        }
    }

    private content[] getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        JSONArray data = forecast.getJSONArray("posts");
         mDataset = new content[data.length()];

        for (int i = 0; i < data.length(); i++) {

            JSONObject jsonDay = data.getJSONObject(i);
            content day = new content();

            day.setId(jsonDay.getInt("id"));
            day.setUrl(jsonDay.getString("url"));
            day.setTitle(jsonDay.getString("title"));
            day.setDate(jsonDay.getString("date"));
            day.setAuthor(jsonDay.getString("author"));
            day.setThumbnail(jsonDay.getString("thumbnail"));
            mDataset[i] = day;
        }
        return mDataset;
    }

    // This will check if there is a net work conection
    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;
    }
}
Jon Kussmann
PLUS
Jon Kussmann
Courses Plus Student 7,254 Points

I figured it was a little easier to just post what I mean. Please try this out and let me know.

public class MainActivity extends ActionBarActivity {



    public String url = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
    public static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;

    content[] mDataset;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setLayoutManager(layoutManager);


        if(isNetworkAvailable()) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            getCurrentDetails(jsonData);

                            mAdapter = new MyAdapter(mDataset);
                            mRecyclerView.setAdapter(mAdapter);


                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    } catch (JSONException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                }
            });
        }
    }

    private content[] getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        JSONArray data = forecast.getJSONArray("posts");
         mDataset = new content[data.length()];

        for (int i = 0; i < data.length(); i++) {

            JSONObject jsonDay = data.getJSONObject(i);
            content day = new content();

            day.setId(jsonDay.getInt("id"));
            day.setUrl(jsonDay.getString("url"));
            day.setTitle(jsonDay.getString("title"));
            day.setDate(jsonDay.getString("date"));
            day.setAuthor(jsonDay.getString("author"));
            day.setThumbnail(jsonDay.getString("thumbnail"));
            mDataset[i] = day;
        }
        return mDataset;
    }

    // This will check if there is a net work conection
    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;
    }
}
alex gwartney
alex gwartney
8,849 Points

nope getting this error now? android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Jon Kussmann
Jon Kussmann
Courses Plus Student 7,254 Points

You are getting that error because you are attempting to change the view from a thread that is not the Main(UI) thread.

alex gwartney
alex gwartney
8,849 Points

so would i need to implement a runnable and could that be because its on the adapter file and not in the on create? If not how could i go about fixing this?

Jon Kussmann
Jon Kussmann
Courses Plus Student 7,254 Points

Yes, you're on the right track.

runOnUiThread(new Runnable() {
     @Override
     public void run() {
         mAdapter = new MyAdapter(mDataset);
         mRecyclerView.setAdapter(mAdapter);
});

If you surround your current 2 lines where you set the adapter with this, it should work.

Let me know if you need me to post your entire Activity.

Jon Kussmann
PLUS
Jon Kussmann
Courses Plus Student 7,254 Points

Try making reference to, and setting the layout manager for the recyclerview directly inside onCreate as opposed to waiting for a response from your network request. You can still just set the adapter after you get your JSON response.

alex gwartney
alex gwartney
8,849 Points

so w hen i call the layoumanager out side the network request i get android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Jon Kussmann
Jon Kussmann
Courses Plus Student 7,254 Points

I just checked your Github, you are not setting a LayoutManager for the recyclerview. This will cause a NullPointerException.

alex gwartney
alex gwartney
8,849 Points
public class MainActivity extends ActionBarActivity {


    public String url = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
    public static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;

    content[] mDataset;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setLayoutManager(layoutManager);



        if(isNetworkAvailable()) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            getCurrentDetails(jsonData);

                            LinearLayoutManager lm = new LinearLayoutManager(getApplicationContext());
                            lm.setOrientation(LinearLayoutManager.VERTICAL);
                            mRecyclerView.setLayoutManager(lm);

                            mAdapter = new MyAdapter(mDataset);
                            mRecyclerView.setAdapter(mAdapter);

                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    } catch (JSONException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                }
            });
        }


    }


    private content[] getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);

        JSONArray data = forecast.getJSONArray("posts");

         mDataset = new content[data.length()];

        for (int i = 0; i < data.length(); i++) {

            JSONObject jsonDay = data.getJSONObject(i);
            content day = new content();

            day.setId(jsonDay.getInt("id"));
            day.setUrl(jsonDay.getString("url"));
            day.setTitle(jsonDay.getString("title"));
            day.setDate(jsonDay.getString("date"));
            day.setAuthor(jsonDay.getString("author"));
            day.setThumbnail(jsonDay.getString("thumbnail"));
            mDataset[i] = day;
        }


        return mDataset;

    }


    // This will check if there is a net work conection
    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;
    }
}
alex gwartney
alex gwartney
8,849 Points

could post a example for me because i though it was at least for what was posted above?

alex gwartney
alex gwartney
8,849 Points

yea if you could that would help thanks.

alex gwartney
alex gwartney
8,849 Points

OMG IT FINALY WORKS THANK GOD IT FINALY WORKS Thanks to all of you guys i really apreicate the help

alex gwartney
alex gwartney
8,849 Points

i added the run ui before but not in the right order that you have it thank you so much omg i have been trying to do this for weeks lol im so happy!

alex gwartney
alex gwartney
8,849 Points

find it funny how three of us could figure this out but 6 people on stack over flow couldn't figure it out lol