I'm trying to pre-populate a FragmentStatePagerAdapter with a list of objects but I cannot instantiate a new fragment.
Background:
My PagerAdapter consists of an ArrayList of Msg objects (mMsgConvoList). MsgConvoList is an ArrayList of all messages from a given thread.
The partitioning of mMsgConvoList creates sublists of 3 msgs each (msgSublist).
Each sublist is put through the while loop to be handled by the PagerAdapter in creating new fragments, and adding additional textviews:
How the logic in the while loop works:
If the count == 2, that means there should be a new fragment, otherwise if the count is 1 to 0, locate the currentFragment and add the Msg (this is where the error occurs).
Error:
The error is occurring after the count == 2. The currentFragment is NULL on the 'else' portion of the while loop (count = 1 or 0). It seems like instantiateItem on the MsgFragment is never called. I'm not sure why this doesn't work when using the loop below.
Caused by: java.lang.NullPointerException
at to.testing.viewpagertest.MsgPagerActivity.onCreate(MsgPagerActivity.java:55)
If I remove the all the code within the 'else' condition from while loop, the fragment is created and the object is added to the text view:
if (count == 2){
mAdapter.addMessages(msgSublist.get(count));
mAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(mAdapter.getCount(), true);
This tells me a few things: The above code, outside of the while loop works, so the dataset is working correctly inside the textView and the fragment is being created successfully. It is only when I try to add an additional Msg object to the existing Array, that the currentFragment never seems to get created. Any suggestions would be much appreciated.
MsgPagerActivity:
if(mMsgConvoList.size() > 0) {
List msgPartitions = daoMsg.partitionArray(mMsgConvoList, 3);
mAdapter = new CustomPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);
for(int i = msgPartitions.size() - 1; i >= 0; i--){
//extract msg objects from each sublist
List<Msg> msgSublist = (List<Msg>)msgPartitions.get(i);
int count = msgSublist.size() -1;
while(count >= 0){
if (count == 2){
mAdapter.addMessages(msgSublist.get(count));
mAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(mAdapter.getCount(), true);
}else{
mViewPager.setCurrentItem(mAdapter.getCount(), true);
MsgFragment currentFragment = (MsgFragment)mAdapter.getFragmentAtPosition(
mAdapter.getCount() - 1);
currentFragment.addMessage(msgSublist.get(count));
}
count--;
}