我在尝试更新 ViewPager 片段内的片段中的 ListView 时遇到问题。整个场景是 FragmentActivity 就像在 Fragment 之间进行通信的基础一样工作。
具体来说,ListFragment 单选片段在 FragmentActivity 中发送一个对象引用,然后将其重定向到 ViewPager 片段,该片段反过来应该更新它的另一个片段子片段。
一切似乎都很完美,第一次创建的 ViewPager 片段显示了我需要的数据,但是,当你在 ListFragment 中选择一行时,它会启动这个过程,同时进入这段代码中的 ViewPager 片段,
public void refreshDataWithClassType(ClassType classType) {
Log.d(TAG, "Should refresh data");
FragmentPagerAdapter fragmentPagerAdapter = (FragmentPagerAdapter) viewPager.getAdapter();
for(int i = 0; i < fragmentPagerAdapter.getCount(); i++) {
ExamsListFragment viewPagerFragment = (ExamsListFragment) fragmentPagerAdapter.getItem(i);
if(viewPagerFragment != null) {
// Do something with your Fragment
// Check viewPagerFragment.isResumed() if you intend on interacting with any views.
viewPagerFragment.refreshExams(classType.getClassTypeId());
}
}
}
我只是将消息发送到每个 ViewPagerFragment 以刷新我的数据(考试)。但是一段时间后我得到 NullPointerException 我发现在 refreshExams 方法中,
public void refreshExams(int classTypeId) {
Bundle args = new Bundle();
args.putInt(KEY_POSITION, getArguments().getInt(KEY_POSITION));
args.putInt(KEY_CLASS_TYPE, classTypeId);
setArguments(args);
getRepositoryExams();
if (examsArrayAdapter == null) Log.d(TAG, "ExamsArrayAdapter is NULL");
if (getActivity() == null) Log.d(TAG, "Activity is NULL");
if (examsList.size() == 0) {
examsArrayAdapter.clear();
examsArrayAdapter.notifyDataSetChanged();
} else {
examsArrayAdapter = new ExamsArrayAdapter(getActivity(), R.layout.exam_row_layout, (ArrayList<Exam>) examsList);
listView.setAdapter(examsArrayAdapter);
}
}
现在,即使我已经应该拥有这个 Fragment 实例,第一次创建它就可以了,
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootView = inflater.inflate(R.layout.exams_list_fragment, container, false);
listView = (ListView) rootView.findViewById(R.id.examsListView);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
callBackExamListener = (OnExamSelectedListener) activity;
} catch (ClassCastException ex) {
throw new ClassCastException(activity.toString() + " must implement OnExamSelectedListener");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getRepositoryExams();
examsArrayAdapter = new ExamsArrayAdapter(getActivity(), R.layout.exam_row_layout, (ArrayList<Exam>) examsList);
listView.setAdapter(examsArrayAdapter);
listView.setOnItemClickListener(listRowItemClickListener);
}
getActivity() 和examsArrayAdapter 为NULL ????
如何解决这个问题?
先感谢您!