-2

I've got an issue with setting an adapter to the ViewPager. Each time i get a NullObjectReference error. What's wrong with my code?

1) Layout:

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

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.view.PagerTabStrip
        android:id="@+id/pager_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:paddingBottom="4dp"
        android:paddingTop="4dp" />

</android.support.v4.view.ViewPager>
</LinearLayout>

2) Java class:

public class FoodFragment extends Fragment {

Toolbar toolbar;
ViewPager viewPager;
TabsPagerAdapter pagerAdapter;


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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    setRetainInstance(true);

      ((AppCompatActivity)getActivity())
    .getSupportActionBar().setDisplayShowTitleEnabled(true);
    ((AppCompatActivity)getActivity())
    .getSupportActionBar().setTitle(R.string.food);
    toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(Color.parseColor("#f6a632"));

    pagerAdapter = new    TabsPagerAdapter(getActivity()
   .getSupportFragmentManager());
    viewPager = (ViewPager) getActivity().findViewById(R.id.view_pager);
    viewPager.setAdapter(pagerAdapter);

    return inflater.inflate(R.layout.fragment_food, container, false);
}
}

I always get this error when calling viewPager.setAdapter(pagerAdapter); line.

fregomene
  • 155
  • 1
  • 11

1 Answers1

0

The reason is that your onCreateView. In fragment, you need to first inflate the view for fragment first, and then findViewById from this view. You may see an example below:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_food, container, false);

    // get your view by: rootView.findViewById()
    // for example:
    viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);

    // do others...

    return rootView;
}
Alan
  • 296
  • 1
  • 5