我有一個問題想更新這是一個ViewPager片段內的片段將ListView中訪問getActivity()。整個場景是FragmentActivity像片段之間進行通信的基礎一樣工作。裏面怎麼ViewPager片段是一個片段
具體地,一個單一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);
}
}
現在連我已經應該有片段的這種情況下,它的確定是beign創建它的第一次,
@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 ????
如何解決這個問題?
預先感謝您!
謝謝史蒂文,與正確的方法合作! – 2013-02-28 13:46:58