Skip to content

Instantly share code, notes, and snippets.

@tanhauhau
Created June 27, 2015 02:06
Show Gist options
  • Save tanhauhau/78a1349bbfd59de02886 to your computer and use it in GitHub Desktop.
Save tanhauhau/78a1349bbfd59de02886 to your computer and use it in GitHub Desktop.
Looping Android Cursor. Saving the time to write the loop each time and close the cursor
public class CursorLooper<K>{
public interface Extract<K>{
public K extract(Cursor cursor);
}
private Extract<K> extract;
public CursorLooper(Extract<K> extract) {
this.extract = extract;
}
public K getFirst(Cursor cursor){
K item = null;
if(cursor.moveToFirst()) {
item = extract.extract(cursor);
}
try { cursor.close(); }catch(Exception e){}
return item;
}
public ArrayList<K> getList(Cursor cursor){
ArrayList<K> list = new ArrayList<>();
if (cursor.moveToFirst()){
do {
K item = extract.extract(cursor);
list.add(item);
}while(cursor.moveToNext());
}
try { cursor.close(); }catch(Exception e){}
return list;
}
public ArrayList<K> getList(Cursor... cursors){
ArrayList<K> list = new ArrayList<>();
for(Cursor cursor : cursors) {
if (cursor.moveToFirst()) {
do {
K item = extract.extract(cursor);
list.add(item);
} while (cursor.moveToNext());
}
try {
cursor.close();
} catch (Exception e) {
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment