简体   繁体   中英

Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' android

I have some problem when I set RecyclerViewAdapter

I get error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference

in line mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());

How to fix it

for (ProfileFeedListModelTwo.PostBean.PollBean pollBean : pp){
   pollBeanArrayList.add(pollBean);}

 adapDetailTopicPoll = new AdapDetailTopicPoll(pollBeanArrayList,getContext());
            mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(adapDetailTopicPoll);

getActivity() is null . You are probably calling this method before your activity is attached to your fragment.

From the documentation :

Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null

Try and understand the fragment lifecycle and how it is coupled with activity lifecycle .

just use only this mLayoutManager = new LinearLayoutManager(getActivity()); and if you are writing this code in activity then use getApplicationContext()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM