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

前端 未结 3 503
广开言路
广开言路 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:25

    I had this issue in my android activity.The mistake was my Toast was not getting the context or I would prefer to call it reference of the activity.

    Previous code:-

    Toast.makeText(context, "Session Expire..!", Toast.LENGTH_SHORT).show();
    

    Corrected Code:-

    Toast.makeText(activityname.this, "Session Expire..!", Toast.LENGTH_SHORT).show();
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-09 09:34

    Same error I went through! It run well in MainActivity but not in my Fragment class.

    I solved this problem by doing the following 2 things:

    1) In Fragment class, don't declare anything globally like we do in Activity class.

    For example:

    public class HomeFragment extends Fragment {
    
    // DON'T WRITE THIS HERE LIKE YOU DO IN ACTIVITY
    String myArray[] = getResources().getStringArray();
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     ...
    }
    

    Instead, write anything inside

    onCreateView()

    method.

    2) Use

    getActivity()

    method first and then

    getResource() method

      public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
    //WRITE LIKE THIS
     String myArray[] = getActivity().getResources().getStringArray(R.array.itemsList);
    
    ...
    }
    
    0 讨论(0)
提交回复
热议问题