-1

Error information:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.myapplication1, PID: 4782 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication1/com.example.myapplication1.Activity_main}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$**LayoutManager)' on a null object reference

My code in MainActivity:

 RecyclerView recyclerView = findViewById(R.id.recycler_view);                         
 LinearLayoutManager layoutManager = new LinearLayoutManager(this);    
 recyclerView.setLayoutManager(layoutManager);

My app shows "AppName has stopped" "keep stopping", when it runs.I guess the parameter "this" maybe wrong ,because when I don't use fragment and put the RecyclerView in the MainActivity.xml rather than in the fragment.xml ,there is nothing wrong.But the context is too hard for me now ,and it's useless to use the parameter like "getApplicationContext()".

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bcql
  • 11
  • 1
  • 2
  • have you checked if `recyclerView` is `null` or not? My guess is that `findViewById` has returned `null`. – Afshin May 13 '18 at 12:27
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – ADM May 13 '18 at 12:31
  • `recyclerView` is `null`. First check you have called `setContentView` before accessing UI element . And then check if `R.id.recycler_view` is part of that layout or not . – ADM May 13 '18 at 12:32

1 Answers1

1

I use this code in Fragment activity and its work...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_order, container, false);
    requestQueue = Volley.newRequestQueue(getActivity());
   txt_dress = view.findViewById(R.id.text_dress);
   txt_status = view.findViewById(R.id.text_status);
    recyclerView = view.findViewById(R.id.recyclerview_orderlist);
    orderAdapter = new OrderAdapter(getActivity(), orderdataList);
    RecyclerView.LayoutManager mymanag = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(mymanag);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
    recyclerView.setAdapter(orderAdapter);
    myEntry();

    return view;
}
M Ali Khattak
  • 27
  • 1
  • 9