Reputation: 592
I am trying to inflate RecyclerView inside the DialogFragment which is Inside a Fragment. I made RecyclerView Adapter normally as per guidelines.
But I am getting this error java.lang.NullPointerException: Attempt to invoke virtual method 'voidandroid.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
On the line
recyclerView.setLayoutManager(manager);
Here's the complete code
public class AlertFragment extends DialogFragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter2;
RecyclerView.LayoutManager manager;
ArrayList<String> goalname = new ArrayList<String>();
ArrayList<String> goalcategory = new ArrayList<String>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_alert, container, false);
goalname.add("Running");
goalcategory.add("Physical");
goalname.add("Yoga");
goalcategory.add("Physical");
goalname.add("Gym");
goalcategory.add("Physical");
goalname.add("Meditation");
goalcategory.add("Mental");
goalname.add("Puzzle Solving");
goalcategory.add("Habits");
manager = new LinearLayoutManager(getActivity());
recyclerView = (RecyclerView) getActivity().findViewById(R.id.bookhistory);
recyclerView.setLayoutManager(manager);
adapter2 = new GoalListAdapter(goalname, goalcategory,getActivity());
recyclerView.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
return v;
}}
Upvotes: 0
Views: 2120
Reputation: 2781
Obviously it is going to crash, because it's not finding recycler view instance.
Just replace this line:
recyclerView = (RecyclerView) getActivity().findViewById(R.id.bookhistory);
With:
recyclerView = (RecyclerView) v.findViewById(R.id.bookhistory);
Now it will work for you.
Upvotes: 1
Reputation: 100
Your issue is with this line:
recyclerView = (RecyclerView) getActivity().findViewById(R.id.bookhistory);
You really want to get the RecyclerView from the view that you inflated in your fragment on this line
View v = inflater.inflate(R.layout.fragment_alert, container, false);
So to fix this, change the first line of code I mentioned to
recyclerView = (RecyclerView) v.findViewById(R.id.bookhistory);
This is assuming that the DialogFragment contains bookhistory
Upvotes: 0