Skip to content

Instantly share code, notes, and snippets.

@albedinsky
Last active April 23, 2017 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albedinsky/6d38f2d94b85d6000d264d7e1189cc2e to your computer and use it in GitHub Desktop.
Save albedinsky/6d38f2d94b85d6000d264d7e1189cc2e to your computer and use it in GitHub Desktop.
FragmentStatePagerAdapter implementation backed by Cursor data set.
import android.app.Fragment;
import android.app.FragmentManager;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import universum.studios.android.pager.adapter.FragmentStatePagerAdapter;
/**
* @author Martin Albedinsky
*/
public class CursorPagerAdapter extends FragmentStatePagerAdapter {
@SuppressWarnings("unused")
private static final String TAG = "CursorPagerAdapter";
public interface PageFragment {
void setPageId(long id);
long getPageId();
}
private Cursor cursor;
private int idColumnIndex;
public CursorPagerAdapter(@NonNull FragmentManager fragmentManager) {
super(fragmentManager);
}
public void changeCursor(@Nullable Cursor cursor) {
final Cursor oldCursor = this.cursor;
this.cursor = cursor;
if (cursor != null && !cursor.isClosed()) {
this.idColumnIndex = cursor.getColumnIndexOrThrow("_id");
}
notifyDataSetChanged();
if (oldCursor != null && !oldCursor.isClosed()) {
oldCursor.close();
}
}
private boolean isCursorValid() {
return cursor != null && !cursor.isClosed();
}
@Override
public int getCount() {
return isCursorValid() ? cursor.getCount() : 0;
}
@Override
public long getItemId(int position) {
return position >= 0 && position < getCount() && cursor.moveToPosition(position) ?
cursor.getLong(idColumnIndex) :
super.getItemId(position);
}
@Override
public int getItemPosition(Object object) {
if (object instanceof PageFragment && isCursorValid() && cursor.moveToFirst()) {
final long pageId = ((PageFragment) object).getPageId();
do {
if (pageId == cursor.getLong(idColumnIndex)) {
return cursor.getPosition();
}
} while (cursor.moveToNext());
}
return POSITION_NONE;
}
@NonNull
@Override
public Fragment getItem(int position) {
if (!isCursorValid() || !cursor.moveToPosition(position)) {
throw new IllegalStateException("Cannot present data from invalid cursor!");
}
// todo: instantiate your PageFragment implementation here and supply it all necessary data
// todo: from the cursor including the corresponding page id as:
// todo: PageFragment.setPageId(cursor.getLong(idColumnIndex));
return new Fragment();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment