Attempt to invoke virtual method 'android.content.Context.getResources()' on a null object reference

前端 未结 3 507
广开言路
广开言路 2020-12-09 08:48

I try to use a fragment to open a database, however, when I click the button to begin searching, the program unexpectedly terminates and it show the error like this:

3条回答
  •  暖寄归人
    2020-12-09 09:31

    You can't do MainActivity parent=(MainActivity) getActivity(); before onAttach() and after onDetach().

    Since, you are doing at the time of fragment instantiation. The method getActivity will always return null. Also as far as possible don't try to keep your Activity reference in your Fragment. This could cause memory leak if the reference is not nullified properly.

    Use getActivity() or getContext() wherever possible.

    Change your Toast as below:

    Toast.makeText(getContext(), "Please check the number you entered", 
    Toast.LENGTH_LONG).show(); 
    

    or

    Toast.makeText(getActivity(), "Please check the number you entered", 
    Toast.LENGTH_LONG).show();
    

提交回复
热议问题