java.lang.NullPointerException,为什么?

时间:2016-07-07 15:14:38

标签: java android nullpointerexception google-cloud-endpoints

在我的Android应用程序中,它使用谷歌云端点作为可扩展的后端解决方案,我在调用时会在暴露的端点api中获取用户朋友时收到NullPointerException。

最初,在我的片段FriendFragment中,我调用了异步任务类;

new EndpointTask.GetFriends(mUserId, FriendFragment.this).execute();

然后,这个异步任务类调用名为getFriends的端点api方法;

return mApi.getFriends(mUserId).execute().getItems();

这将调用此方法,该方法在api explorer中按预期运行;

@ApiMethod(name = "getFriends", path = "friends", httpMethod = ApiMethod.HttpMethod.GET)
    public List<Profile> getFriends(@Named("userId") String userId) {
        Profile profile = ofy().load().key(Key.create(Profile.class, userId)).now();
        if (profile != null) {
            List<Profile> friends = new ArrayList<>(0);
            for (String friendId : profile.getFriendIds()) {
                Profile friend = ofy().load().key(Key.create(Profile.class, friendId)).now();
                friends.add(friend);
            }
            return friends;
        }
        return null;
    }

返回的List通过它实现的接口发送回片段;

// The interface
public interface OnFetchedFriends {
    void sendFriends(List<Profile> friends);
}

@Override
protected void onPostExecute(List<Profile> friends) {
    super.onPostExecute(friends);
    mListener.sendFriends(friends);
}

// In the fragment
@Override
public void sendFriends(List<Profile> friends) {
    mFriends.clear();
    mFriends.addAll(friends);
    mAdapter.notifyDataSetChanged();
}

然后将此数据传递到适配器,并应在回收站视图中显示在屏幕上;

RecyclerView requestRecyclerView = (RecyclerView) view.findViewById(R.id.friends_recycler_view);
requestRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
requestRecyclerView.setLayoutManager(mLayoutManager);

mAdapter = new FriendAdapter(mFriends);
requestRecyclerView.setAdapter(mAdapter);

这是堆栈跟踪:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.hb.backend.birthpayApi.model.ProfileCollection.getItems()' on a null object reference
    at com.hb.birthpay.utils.EndpointTask$GetFriends.doInBackground(EndpointTask.java:101)
    at com.hb.birthpay.utils.EndpointTask$GetFriends.doInBackground(EndpointTask.java:67)

为什么会发生java.lang.NullPointerException?

0 个答案:

没有答案
相关问题