Javed Ali
Javed Ali

Reputation: 1550

NullPointerException for RecyclerView In fragment

Trying to implement a cards list using the recyclerview inside of a fragment. Every time I run it crashes when trying to open the fragment. I was following this tutorial https://developer.android.com/training/material/lists-cards.html#Dependencies and also this one http://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465

Logcat where it crashes.

    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference

circles_tab.xml snippet

<android.support.v7.widget.RecyclerView
    android:id="@+id/circleList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:layout_marginTop="12dp"/>

CirclesFragment

public class CirclesFragment extends Fragment {

public ArrayList<String> circles = new ArrayList<String>();
public CharSequence[] circlesList;
public String[] circlesArray = new String[circles.size()];
private List<Person> persons;


private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

ButtonFloat FAB;
Dialog dialog;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v =inflater.inflate(R.layout.circles_tab,container,false);

    // Create Cards list

    mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.circleList);
    mRecyclerView.setHasFixedSize(false);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    initializeData();
    mAdapter  = new RVAdapter(persons);
    mRecyclerView.setAdapter(mAdapter);

    return v;
}

private void initializeData(){
    persons = new ArrayList<>();
    persons.add(new Person("Peter Parker", R.drawable.logo));
    persons.add(new Person("Miles Morales",R.drawable.logo));
    persons.add(new Person("Oliver Queen", R.drawable.logo));
}

There are many similar questions with this topic but most of them have not been resolved. Any help would be greatly appreciated.

Thanks everyone

Upvotes: 1

Views: 2782

Answers (1)

M D
M D

Reputation: 47807

Change

 mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.circleList);

to

 mRecyclerView = (RecyclerView)v.findViewById(R.id.circleList);

Upvotes: 7

Related Questions