-2

I'm trying to get a Staggered Grid layout using a RecyclerView in one of my ViewPagers fragments. When I start the app, it immediately crashes and throws this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference at xxx.HomeActivity.onCreate(HomeActivity.java:39) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)

My first thought is that this might be caused by the order in which the views are loaded but i'm not sure. I have a ViewPager with 2 fragments. I have the RecyclerView declared in the first fragments xml, like so:

res/layout/fragment_home.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/home_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Heres the relative parts of my Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    ButterKnife.bind(this);

    setupToolbar();
    setupTabs();

    HomeGridAdapter adapter = new HomeGridAdapter(Contacts.createFakeContacts(20));

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.home_grid);

    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));


}

Here is the first fragments Java file:

public class HomeFragment extends Fragment {

public static final String ARG_PAGE = "ARG_PAGE";

private int mPage;

public static HomeFragment newInstance(int page) {
    Bundle args = new Bundle();
    args.putInt(ARG_PAGE, page);
    HomeFragment fragment = new HomeFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPage = getArguments().getInt(ARG_PAGE);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_home, container, false);
}


}

I dont think i need to post the RecyclerViews adapter code as I dont think that is part of the issue, but if its needed I can.

Any input on this issue is appreciated!

EDIT: As requested, heres my activitys xml file:

<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=".HomeActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"
    android:layout_width="match_parent"
    android:layout_height="75dp"
    style="@style/ToolbarStyle"
    >

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:tabMode="scrollable"/>

</android.support.v7.widget.Toolbar>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"/>

</LinearLayout>
user229044
  • 232,980
  • 40
  • 330
  • 338
Orbit
  • 2,985
  • 9
  • 49
  • 106
  • Where are you instantiating your ViewPager? Can you post your Activity layout xml? It seems your Activity doesn't have the ViewPager loaded on it, so the RecyclerView which is in the ViewPager will not exist on onCreate() resulting in null. – JTY Sep 26 '15 at 04:07
  • Added my activities xml file. The viewpager is binded with butterknife up higher, and the `setupTabs()` method sets up the TabLayout and ViewPager. I didnt include it as i didnt think its part of the issue. – Orbit Sep 26 '15 at 04:17

3 Answers3

1

You are loading activity_home in activity

setContentView(R.layout.activity_home);

and your home_grid is located in first_fragment

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

<android.support.v7.widget.RecyclerView
    android:id="@+id/home_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</RelativeLayout>
Ravi Gadipudi
  • 1,446
  • 1
  • 17
  • 30
  • I'm not sure what your getting at here. – Orbit Sep 26 '15 at 04:18
  • You mentioned wrong xml in activity – N J Sep 26 '15 at 04:19
  • Did you try creating the recyclerview in fragment. Try moving the recyclerview code into fragment from activity. – Ravi Gadipudi Sep 26 '15 at 04:22
  • @Nilesh How is it the wrong activity, re-read the question please. Ravi I tried initiating the recyclerview in both my fragments onCreate and onCreateView methods and got the same error. – Orbit Sep 26 '15 at 04:24
  • setContentView(R.layout.activity_home); in you code which does not contain RecyclerView – N J Sep 26 '15 at 04:26
  • @Nilesh Please leave this question, you have obviously not read or do not understand it. I am completely aware that it does not contain RecyclerView. The RecyclerView is inside one of the fragments in a viewpager. – Orbit Sep 26 '15 at 04:28
1

Within onCreate() of your Activity, first find your ViewPager:

    ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
    MyFragmentPagerAdaptor adaptor = new
        MyFragmentPagerAdapter(getSupportFragmentManager());
    pager.setAdapter(adaptor);

Within the Activity Class, Create a new FragmentPagerAdapter nested class called MyFragmentPagerAdapter, which returns your Fragment on the getItem() method.

Currently, your ViewPager doesn't have any content inside and you are not loading the fragment into the ViewPager. (Purely from the code I see. I may be wrong)

Now that your ViewPager has the fragment content inside, you need a way to access the child View within the fragment (within the Viewpager).

This will not be directly possible, so you need to create a instance of the fragment you are looking for using your adaptor's getItem() method:

Fragment f = (Fragment) adaptor.getItem(pager.getCurrentItem());

Although getCurrentItem() can be replaced with an index pointing directly to your Fragment, which should have already been defined within the getItem().

Finally, You can find your child view within the fragment like so:

RecyclerView theViewINeed = (RecyclerView)f.getView().findViewById(R.id.home_grid);

edit: seems like the Fragment's OnCreateView() is not called during the parent Activity's OnCreate().

Try moving the below code to OnStart. (Put the Fragment reference you obtain from onCreate() as a field, and access it during onStart())

RecyclerView theViewINeed = (RecyclerView)f.getView().findViewById(R.id.home_grid);
JTY
  • 1,009
  • 7
  • 13
  • Thanks for the response. I am not concerned with setting up the ViewPager, as I said in my comment to you im already doing that in a helper method-`setupTabs()`. The Tabs and ViewPager work fine. Anyway, I tried getting the fragment directly using this: `HomeFragment f = (HomeFragment) pagerAdapter.getItem(0);` and then calling f.getView...... but It still threw the same error. – Orbit Sep 26 '15 at 04:56
  • That would mean that getItem(0) is returning null. Maybe you can post the code for the adaptor? I still think that although your getItem() is returning an improper fragment, maybe the fragment itself is not being initialized with your xml layout. Also please post the fragment constructor if possible. – JTY Sep 26 '15 at 05:03
  • Hmm I dont think so. Again my viewPager works flawlessly. I just added a quick if/else log statement and checked `if (pagerAdapter.getItem(0) != null)` and it said it wasn't null so.. I dont think this is an issue with the adapter. I added a log statement right after instantiating the recyclerView to check if its null, and it is. So the problem is this line in my Activity `RecyclerView recyclerView = (RecyclerView) findViewById(R.id.home_grid);` is coming up with `recyclerView` being null, for whatever reason. Any ideas why? – Orbit Sep 26 '15 at 05:13
  • Hmm I think the fragment's OnCreateView() is not called during the Activity's OnCreate(). Try to move the getView().findViewById() code to the onStart of your Activity. I have put an edit to the answer. – JTY Sep 26 '15 at 05:42
-1

You have specified activity_home.xml layout for Activity

while your RecyclerView tag is in fragment_home.xml

try to initialize RecyclerView in fragment Or add RecyclerView tag in activity_home.xml

N J
  • 27,217
  • 13
  • 76
  • 96