TheHardRock TheHardRock - 5 months ago 10
Android Question

How to add a view dynamically inside a fragment

I was making a RecyclerView inside a fragment. I created objects of my RecyclerView Adapter and LinearLayoutManager through the Java code.

public class RFPMenuFragment extends Fragment{

List<MyRFP> myRFPList;
RecyclerView recyclerViewRFP;
RVAdapterRFP rvAdapterRFP;
LinearLayoutManager llm;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.single_feed, container, false);

recyclerViewRFP = (RecyclerView) view.findViewById(R.id.recycler_view_rfp);

initializeData();


rvAdapterRFP = new RVAdapterRFP(myRFPList);
recyclerViewRFP.setAdapter(rvAdapterRFP);

llm = new LinearLayoutManager(getActivity());
recyclerViewRFP.setLayoutManager(llm);

return view;
}


But its giving me a
NullPointerException
on the line having the setAdapter method. Even when I remove the 2 Adapter lines, I get this error on the setLayoutManager method. How do I fix this?

Here's my LogCat:

Process: com.example.h8pathak.jobs, PID: 26848
java.lang.NullPointerException
at com.example.h8pathak.jobs.rfp.RFPMenuFragment.onCreateView(RFPMenuFragment.java:41)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1671)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:532)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)

Answer

Seems that you haven't added the RecyclerView in your single_feed layout.

If this is true, add the following part in the layout you want the RecyclerView to populate the data.

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

And in your case, mention the layout in your RFPMenuFragment.java that'll have the RecyclerView not the single_feed layout (if it does, what its name suggests).