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

前端 未结 3 519
广开言路
广开言路 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: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);
    
    ...
    }
    

提交回复
热议问题