Last active
April 23, 2017 22:39
-
-
Save albedinsky/6d38f2d94b85d6000d264d7e1189cc2e to your computer and use it in GitHub Desktop.
FragmentStatePagerAdapter implementation backed by Cursor data set.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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