Jon
Jon

Reputation: 193

Cursor-driven content in ViewPager

I'd like to use a ViewPager to show several items per page from a single Cursor (originally from a ContentProvider). The layout will be shown as a grid and will include images and text for each item. There will be frequent additions and deletions from the list which need to be reflected in the UI without having to rebuild the data structures (which may preclude some options below).

Current process:

  1. Instantiate cursor in main activity.
  2. Create my own Cursor Adapter class extended from PagerAdapter which takes in the cursor. The cursor is used to determine the number of pages the ViewPager will have through getCount() (and then adjusted according to how many items will be shown per page).
  3. In the Cursor Adapter getItem method, it creates the fragment which will eventually contain a subset of the list.

At this stage, I'm not sure which is the best method to take. Do I:

A. Pass the Cursor and an index to the Fragment to display the next page of results (e.g. having a setCursorIndex( Cursor, int ) method. (Does sharing Cursors across Fragments cause issues even if it's in the same Activity?)

B. Pass in a list of ContentUris strings which would obtain the results. (Would this prevent updates to the list without having to rebuild?)

C. Build an arguments bundle containing the items (a list containing byte arrays for images, and text). (This seems inefficient due to the use of images.)

D. Re-create a new Cursor in each Fragment having received a starting index from the adapter. (Inefficient?)

Many thanks for your help.

Upvotes: 2

Views: 843

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006604

IMHO, the answer is some combination of B and C.

It is C, insofar as you create an arguments Bundle and give it to the Fragment, perhaps using the factory method pattern (e.g., newInstance()). This way, you have all that data in the fragment during configuration changes, if the fragment will be destroyed and recreated.

However, "a list containing byte arrays for images, and text" seems inappropriate. If you already have Uri values (or String representation of Uri values) for the images, put those in the Bundle, and use a centralized image caching solution (such as this one or this one) for ensuring that you only load those images in when needed. Other smallish things ("and text") can just go into the Bundle.

Option A can probably work, but you have to be careful to take into account:

  • configuration changes (what happens when the user rotates the screen and your activity is destroyed/recreated?)
  • the implicit current-row pointer in the Cursor (each fragment will need to moveToPosition() before attempting to read any data)

Upvotes: 2

Related Questions