Skip to content

Instantly share code, notes, and snippets.

@httpdispatch
Created April 23, 2014 10: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 httpdispatch/11210330 to your computer and use it in GitHub Desktop.
Save httpdispatch/11210330 to your computer and use it in GitHub Desktop.
Wrapper around android android.database.Cursor which allows to skip number of items by the their position
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.database.AbstractCursor;
import android.database.Cursor;
/**
* Extended solution of U Avalos taken from here
* http://stackoverflow.com/a/18139147/527759
*
* This is a wrapper around android
* Cursor which may be used in the CursorAdapter to support item deletion
* without cursor requery or data reload.
*
* Cursor allows to add multiple indexes
* which should be skipped during iterations.
*
* @author Eugene Popovich, U Avalos
*/
public class CursorWithDelete extends AbstractCursor {
private List<Integer> positionsToIgnore = new ArrayList<Integer>();
private Cursor cursor;
public CursorWithDelete(Cursor cursor) {
this.cursor = cursor;
}
@Override
public boolean onMove(int oldPosition, int newPosition) {
cursor.moveToPosition(adjustPosition(newPosition));
return true;
}
public int adjustPosition(int newPosition) {
int ix = Collections.binarySearch(positionsToIgnore, newPosition);
if (ix < 0) {
ix = -ix - 1;
} else {
ix++;
}
int newPos;
int lastRemovedPosition;
do {
newPos = newPosition + ix;
lastRemovedPosition = positionsToIgnore.size() == ix ? -1 : positionsToIgnore.get(ix);
ix++;
} while (lastRemovedPosition >= 0 && newPos >= lastRemovedPosition);
return newPos;
}
@Override
public int getCount() {
return cursor.getCount() - positionsToIgnore.size();
}
@Override
public String[] getColumnNames() {
return cursor.getColumnNames();
}
@Override
public String getString(int column) {
return cursor.getString(column);
}
@Override
public short getShort(int column) {
return cursor.getShort(column);
}
@Override
public int getInt(int column) {
return cursor.getInt(column);
}
@Override
public long getLong(int column) {
return cursor.getLong(column);
}
@Override
public float getFloat(int column) {
return cursor.getFloat(column);
}
@Override
public double getDouble(int column) {
return cursor.getDouble(column);
}
@Override
public boolean isNull(int column) {
return cursor.isNull(column);
}
/**
* Call if you want to hide some position from the result
*
* @param position in the AdapterView, not the cursor position
*/
public void deleteItem(int position) {
position = adjustPosition(position);
int ix = Collections.binarySearch(positionsToIgnore, position);
positionsToIgnore.add(-ix - 1, position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment