Created
June 27, 2015 02:06
-
-
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
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
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