Skip to content

Instantly share code, notes, and snippets.

@iTwenty
Last active August 29, 2015 14:14
Show Gist options
  • Save iTwenty/58212c82e577686071d3 to your computer and use it in GitHub Desktop.
Save iTwenty/58212c82e577686071d3 to your computer and use it in GitHub Desktop.
CursorPagerAdapter that doesn't need projection. Added changeCursor method that closes old cursor after swapping
package com.t3methods.happysmiles.app.ui.adapters;
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<? extends F> mFragmentClass;
private Cursor mCursor;
public CursorPagerAdapter( FragmentManager fm, Class<? extends F> fragmentClass, Cursor cursor )
{
super( fm );
this.mFragmentClass = fragmentClass;
this.mCursor = cursor;
}
@Override
public F getItem( int position )
{
if( mCursor == null ) // shouldn't happen
return null;
mCursor.moveToPosition( position );
F frag;
try
{
frag = mFragmentClass.newInstance();
}
catch( Exception ex )
{
throw new RuntimeException( ex );
}
Bundle args = new Bundle();
for( int i = 0; i < mCursor.getColumnNames().length; ++i )
{
// Get the type of field so the arguments can be properly set.
int type = mCursor.getType( i );
switch( type )
{
case Cursor.FIELD_TYPE_BLOB:
args.putByteArray( mCursor.getColumnName( i ), mCursor.getBlob( i ) );
break;
case Cursor.FIELD_TYPE_FLOAT:
args.putFloat( mCursor.getColumnName( i ), mCursor.getLong( i ) );
break;
case Cursor.FIELD_TYPE_INTEGER:
args.putInt( mCursor.getColumnName( i ), mCursor.getInt( i ) );
break;
case Cursor.FIELD_TYPE_STRING:
args.putString( mCursor.getColumnName( i ), mCursor.getString( i ) );
break;
default:
break;
}
}
frag.setArguments( args );
return frag;
}
@Override
public int getCount()
{
if( mCursor == null )
return 0;
else
return mCursor.getCount();
}
public void changeCursor( Cursor c )
{
Cursor old = swapCursor( c );
if( null != old ) old.close();
}
public Cursor swapCursor( Cursor c )
{
if( mCursor == c )
return null;
Cursor oldCursor = mCursor;
this.mCursor = c;
notifyDataSetChanged();
return oldCursor;
}
public Cursor getCursor()
{
return mCursor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment