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

Getting NullPointerException on viewPager.setAdapter

im getting a NullPointerException on this: viewPager.setAdapter(adapter), Im using a GitHub library but ive seen videos of people implementing this stuff, but im getting this particular error, please help me

here's the complete code:

public class MessageActivity extends FragmentActivity implements MaterialTabListener {

protected MaterialTabHost tabHost;
protected ViewPager viewPager;
protected ViewPagerAdapter adapter;

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

    tabHost = (MaterialTabHost) findViewById(R.id.materialTabHost);
    adapter = new ViewPagerAdapter(getSupportFragmentManager());

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(adapter);

8 Answers

One possible root cause for your problem would be that fact that the line:

viewPager = (ViewPager) findViewById(R.id.viewPager);

produces null as a result. That would cause the NPE down the road when you try to call setAdapter on viewPager down the road.

My question is this: did you define the id.viewPager resource id somewhere in your layout XML files. If that resource ID is not defined, them the findViewById(R.id.viewPager) invocation will return null which may explain your problem.

Posting a logcat dump would also help with identifying the problem.

Here is my xml file:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MessageActivity">

<it.neokree.materialtabs.MaterialTabHost
    android:id="@+id/materialTabHost"
    android:layout_width="match_parent"
    android:layout_height="48dp" />

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

Yep. It looks like the id.viewPager is defined in your XML layout resource. It must be something else.

Can you go to you terminal and type:

$ adb logcat

Run your app, let it crash and copy/paste here the output from the console. It should give us the exact line where the NPE occurs.

heres my logCat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.juan.login/com.example.juan.login.MessageActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) at android.app.ActivityThread.access$600(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5103) 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:737) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.example.andrey.login.MessageActivity.onCreate(MessageActivity.java:32) at android.app.Activity.performCreate(Activity.java:5133) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)             at android.app.ActivityThread.access$600(ActivityThread.java:141)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)             at android.os.Handler.dispatchMessage(Handler.java:99)             at android.os.Looper.loop(Looper.java:137)             at android.app.ActivityThread.main(ActivityThread.java:5103)             at java.lang.reflect.Method.invokeNative(Native Method)

Ok,

So the NPE seems to occur at line 32 in the following class com.example.andrey.login.MessageActivity.

Is this a class you wrote yourself, or is it a class you are just extending from an external library? Do you have the code for that class? If so, can you post the line of code around line 32 in that class?

Thanks.

no no it is a class i wrote, i dont know why at the beginning it says juan.login :o!!! i have clean it and rebuild it and that name changed to mine, but the error stays the same. The line 32 is viewPager.setAdapter(adapter); and the whole picture is this:

public class MessageActivity extends FragmentActivity implements MaterialTabListener {

protected MaterialTabHost tabHost;
protected ViewPager viewPager;
protected ViewPagerAdapter adapter;

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

    tabHost = (MaterialTabHost) findViewById(R.id.materialTabHost);
    adapter = new ViewPagerAdapter(getSupportFragmentManager());

    viewPager = (ViewPager) findViewById(R.id.viewPager);


        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                tabHost.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < adapter.getCount(); i++) {
            tabHost.addTab(
                    tabHost.newTab()
                            .setText(adapter.getPageTitle(i))
                            .setTabListener(this)
            );
        }


}

If line 32 is viewPager.setAdapter(adapter); then:

  • either viewPager is null
  • or adapter is null

Can you place a breakpoint at line 32 and see which one of these references are null?

the LogCat tells me the viewPager is the one that is null

This means it cannot find R.id.viewPager identifier. This usually happens when the generated R.java file (the one that contains all the handlers to the UI resources) gets out of sync with your XML layout source files. Can you try to clean and re-build the whole project?

I have cleaned it and rebuild it but still doesnt work i think the error is in this line on the xml.--> android.support.v4.view.ViewPager

the whole thing is : <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" />

<android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

Can you open up the generated file R.java and look for viewPager and see if that symbol is defined? I assume it is, otherwise it wouldn't have compiled in the first place. This is very weird...

and I havent touch the R.java file of Android Studio :(

I know, you should touch it. In fact even if you did, that file is re-generated every time to do another compilation; so it would not matter much if you did touch it by hand.

i dont know why but my gen folder is empty... but if its empy why is it running?.... this is so strange

i found it here it is:

public static final int viewPager=0x7f0a0073;

and its located here in this class: public static final class id {}, seriously I dont know what this is happening, what can you recommend me to do?

I solved it... I was setting the wrong xml on setContentView in my Activity.....what a fail!!! but you helped me a lot thanks Andrei