简体   繁体   中英

RecyclerView inside DialogFragment inside Fragment

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;
}}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM