Skip to content

Instantly share code, notes, and snippets.

@mlc
Created June 22, 2012 21:26
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mlc/2975296 to your computer and use it in GitHub Desktop.
Save mlc/2975296 to your computer and use it in GitHub Desktop.
package com.meetup.adapter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class CursorPagerAdapter<F extends Fragment> extends FragmentStatePagerAdapter {
private final Class<F> fragmentClass;
private final String[] projection;
private Cursor cursor;
public CursorPagerAdapter(FragmentManager fm, Class<F> fragmentClass, String[] projection, Cursor cursor) {
super(fm);
this.fragmentClass = fragmentClass;
this.projection = projection;
this.cursor = cursor;
}
@Override
public F getItem(int position) {
if (cursor == null) // shouldn't happen
return null;
cursor.moveToPosition(position);
F frag;
try {
frag = fragmentClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Bundle args = new Bundle();
for (int i = 0; i < projection.length; ++i) {
args.putString(projection[i], cursor.getString(i));
}
frag.setArguments(args);
return frag;
}
@Override
public int getCount() {
if (cursor == null)
return 0;
else
return cursor.getCount();
}
public void swapCursor(Cursor c) {
if (cursor == c)
return;
this.cursor = c;
notifyDataSetChanged();
}
public Cursor getCursor() {
return cursor;
}
}
@sub1ime
Copy link

sub1ime commented Jan 12, 2014

Looks like exactly what I'm looking for but I wish I could see the class that calls this adapter.

@sergiandreplace
Copy link

You saved me a lot of time sir, thanks!

@drmatrix
Copy link

i need help
how to implement that in FragmentActivity

@am1n
Copy link

am1n commented Jul 8, 2014

Thanks for this code, it works great, although I adapted it a bit as I didn't need the generic version. I use it with a loader and loader callbacks in the support library, and the method names make it easy to use instead of a standard adapter.

@155martinmoreno
Copy link

I would add:

public Cursor swapCursor(Cursor newCursor)
{
    if (cursor == newCursor)
    {
        return null;
    }

    Cursor oldCursor = cursor;

    this.cursor = newCursor;
    notifyDataSetChanged();

    return oldCursor;
}

/**
 * Change the underlying cursor to a new cursor. If there is an existing cursor it will be
 * closed.
 *
 * @param cursor The new cursor to be used
 */
public void changeCursor(Cursor cursor)
{
    Cursor old = swapCursor(cursor);
    if (old != null)
    {
        old.close();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment