I'm new to the Android Compatibility Library with Fragments and the ViewPager (android.support.v4) I'm having loads of fun with no JavaDocs in Eclipse
I was following this Tutorial on ViewPager and Fragments
I reused some of the code to add Fragments to a ViewPager while iterating through a custom object in a foreach loop
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
for (CustomObjectClass object : getAllBalances()) {
Fragment fragment = Fragment.instantiate(this,
SomeCustomFragmentClass.class.getName());
// Line below is where stacktrace points to with NullPointer
ListView lv = ((ListView) fragment.getActivity().findViewById(
R.id.someListView));
// proceed setting a custom adapter to lv (ListView) then adding to list of fragments
fragments.add(fragment);
}
this.mPagerAdapter = new PagerAdapter(
super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);
}
After reading other answers and 'google'n' all day I've come to the conclusion that It's probably something to do with the Fragment not being fully initialized by the time I go referencing one of its views.
Or I'm even farther off and have no clue what I'm doing.
I've tried putting methods inside the fragment class to set the adapter, and calling them on the onViewCreated()
which worked but with the current layout of my code would make that slightly impractical.
I'm open to any alternatives if what I'm doing is incorrect or inefficient
My goal is to iterate through my CustomObject that contains the data to populate each Fragments ListView and put each Fragment into a ViewPager
Well so far the only possible solution was doing what i didn't want to do.
in the Fragment SomeCustomFragmentClass
private CustomObjectClass object; //with getters and setters
@Override
public void onViewCreated(View view, Bundle savedInstanceState){
ListView lv = ((ListView) view.findViewById(R.id.somelistView));
((ViewPagerActivity) this.getActivity()).setAdapter(object, lv);
}
and in my foreach loop ViewPagerActivity
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
for (CustomObjectClass object : getAllBalances()) {
Fragment fragment = Fragment.instantiate(this,
SomeCustomFragmentClass.class.getName());
((SomeCustomFragmentClass) fragment).setObject(object);
fragments.add(fragment);
}
this.mPagerAdapter = new PagerAdapter(
super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);
}