改造:片段列表视图



我正在使用带有三个片段的选项卡。我试图通过使用改造 2 在片段 (TwoFragment( 中加载一些数据。但我得到了
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter('

public class TwoFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View rootView =   inflater.inflate(R.layout.fragment_two, container, false);
        final ListView listView=(ListView)rootView.findViewById(R.id.listviewupgradeTo);
        LoginService loginService = ServiceGenerator.createService(LoginService.class,"abc","123");
        Call<List<UpgradeInfo>> call=loginService.getListInfo(i);
        call.enqueue(new Callback<List<UpgradeInfo>>() {
            @Override
            public void onResponse(Call<List<UpgradeInfo>> call, Response<List<UpgradeInfo>> response) {
                List<UpgradeInfo> list=response.body();
                listView.setAdapter(new UpgrageInfoRecordListViewAdapter(getContext(),list));
            }
            @Override
            public void onFailure(Call<List<UpgradeInfo>> call, Throwable t) {
            }
        });
        return rootView;
    }

}

从连接接收模型时,应始终执行空检查。您还应该检查响应是否有效。最后,该列表不是响应模型的正文。它包含在体内。这样:

if (response.isSuccessful() && response.body() != null) { // make this first check
    List<UpgradeInfo> list=response.body().getUpgradeInfo(); // here, you should get the list from within the model
    if (list != null) { // make the null check
        listView.setAdapter(new 
UpgrageInfoRecordListViewAdapter(getContext(),list));
    }
}

让我知道结果如何。

最新更新