I can\'t update the content in ViewPager.
What is the correct usage of methods instantiateItem() and getItem() in FragmentPagerAdapter class?
I was using onl
I have encountered this problem and finally solved it today, so I write down what I have learned and I hope it is helpful for someone who is new to Android's ViewPager
and update as I do. I'm using FragmentStatePagerAdapter
in API level 17 and currently have just 2 fragments. I think there must be something not correct, please correct me, thanks.
Serialized data has to be loaded into memory. This can be done using a CursorLoader
/AsyncTask
/Thread
. Whether it's automatically loaded depends on your code. If you are using a CursorLoader
, it's auto-loaded since there is a registered data observer.
After you call viewpager.setAdapter(pageradapter)
, the adapter's getCount()
is constantly called to build fragments. So if data is being loaded, getCount()
can return 0, thus you don't need to create dummy fragments for no data shown.
After the data is loaded, the adapter will not build fragments automatically since getCount()
is still 0, so we can set the actually loaded data number to be returned by getCount()
, then call the adapter's notifyDataSetChanged()
. ViewPager
begin to create fragments (just the first 2 fragments) by data in memory. It's done before notifyDataSetChanged()
is returned. Then the ViewPager
has the right fragments you need.
If the data in the database and memory are both updated (write through), or just data in memory is updated (write back), or only data in the database is updated. In the last two cases if data is not automatically loaded from the database to memory (as mentioned above).
The ViewPager
and pager adapter just deal with data in memory.
So when data in memory is updated, we just need to call the adapter's notifyDataSetChanged()
. Since the fragment is already created, the adapter's onItemPosition()
will be called before notifyDataSetChanged()
returns. Nothing needs to be done in getItemPosition()
. Then the data is updated.