Skip to content

Instantly share code, notes, and snippets.

@operando
Last active August 29, 2015 14:06
Show Gist options
  • Save operando/0b5ff0bacbffecb0730a to your computer and use it in GitHub Desktop.
Save operando/0b5ff0bacbffecb0730a to your computer and use it in GitHub Desktop.
【Android】Cursorをいじるメソッドで気をつけたいPositionの話 ref: http://qiita.com/operandoOS/items/6527b30f7e9bd8b60200
public static void dumpLastRecord(Cursor cursor) {
Log.d("dumpLastRecord", "=============");
if (cursor != null) {
cursor.moveToPosition(-1);
if (cursor.moveToLast()) {
String[] columnNames = cursor.getColumnNames();
int length = columnNames.length;
for (int i = 0; i < length; i++) {
String value;
try {
value = cursor.getString(i);
} catch (SQLiteException e) {
value = "<unprintable>";
}
Log.d("dumpLastRecord", columnNames[i] + " : " + value);
}
}
}
Log.d("dumpLastRecord", "=============");
}
Cursor c = db.query(....);
c.moveToFirst();
Log.d("Before Cursor Position","" + c.getPosition());
dumpLastRecord(c);
Log.d("After Cursor Position","" + c.getPosition());
D/Bfter Cursor Position﹕ 0
D/After Cursor Position﹕ 9
public static void dumpLastRecord(Cursor cursor) {
Log.d("dumpLastRecord", "===========================");
if (cursor != null) {
int startPosition = cursor.getPosition();
cursor.moveToPosition(-1);
if (cursor.moveToLast()) {
String[] columnNames = cursor.getColumnNames();
int length = columnNames.length;
for (int i = 0; i < length; i++) {
String value;
try {
value = cursor.getString(i);
} catch (SQLiteException e) {
value = "<unprintable>";
}
Log.d("dumpLastRecord", columnNames[i] + " : " + value);
}
}
cursor.moveToPosition(startPosition);
}
Log.d("dumpLastRecord", "===========================");
}
public static void dumpLastRecord(Cursor cursor) {
Log.d("dumpLastRecord", "===========================");
if (cursor != null) {
int startPosition = cursor.getPosition(); // Cursorをいじる前に現在のPositionを一旦変数に保持
// 省略
cursor.moveToPosition(startPosition); // Cursorをいじり終わったら元のPositionに戻してあげる
}
Log.d("dumpLastRecord", "===========================");
}
D/Bfter Cursor Position﹕ 0
D/After Cursor Position﹕ 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment