NullPointException in RecyclerView

后端 未结 1 605
刺人心
刺人心 2021-01-27 12:12

I try to download list from server in AsyncTask and put it into recyclerView. However, I still get NullPointException on RecyclerView and have no idea why. I set LayoutManager a

1条回答
  •  情歌与酒
    2021-01-27 13:03

    Change Your AsyncTask Like This

                            public class GetUsersAsyncTask extends AsyncTask> {
    
    
                         public Context mContext;
                         private ChatMainFragment mFragment;
                         private RecyclerView mUserRecyclerView;
    
                         public GetUsersAsyncTask(ChatMainFragment fragment,RecyclerView mRListView) {
                             this.mFragment = fragment;
                             this.mUserRecyclerView=mRListView;
                         }
    
    
                         @Override
                         protected List doInBackground(String... params) {
                             List userList = new ArrayList<>();
                             try {
                                 userList  = ServerConnector.getInstance(mContext).getChatUserList();
                              /*requestEnds(userList);*/
                             } catch (ServerConnectorException e) {
                                 e.printStackTrace();
                             }
    
                             return userList;
                         }
    
                         @Override
                         protected void onPostExecute(List chatUserListItems) {
                             Log.e(TAG, "onPostExecute: ");
                             userList = chatUserListItems ;
                             ChatMainAdapter adapter = new ChatMainAdapter(getActivity().getApplicationContext(), userList);
                            mUserRecyclerView.setAdapter(adapter);
                            mUserRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
                             adapter.notifyDataSetChanged();
    
    
                         }
                         }
    

    and when you initiate your async class in onCreateView initiate it like this

     mUserListView = (RecyclerView)view.findViewById(R.id.user_list);
    GetUsersAsyncTask task = new GetUsersAsyncTask(this,mUserListView);
    

    Just replace the code and it should work as expected .. Hope this helps

    0 讨论(0)
提交回复
热议问题