Created
June 22, 2012 21:26
-
-
Save mlc/2975296 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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; | |
} | |
} |
You saved me a lot of time sir, thanks!
i need help
how to implement that in FragmentActivity
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.
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
Looks like exactly what I'm looking for but I wish I could see the class that calls this adapter.