Cleanup: AutoCloseableIterator now handles the cursor.

This commit is contained in:
Dennis Guse
2025-12-04 17:09:31 +01:00
parent 12f0c3313f
commit d49d6c9857
19 changed files with 105 additions and 236 deletions
@@ -1,29 +1,70 @@
package de.dennisguse.opentracks.util;
import android.database.Cursor;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import java.util.Iterator;
import java.util.NoSuchElementException;
//TODO All children use a cursor. Move this shared functionality here.
public abstract class AutoCloseableIterator<T> implements Iterator<T>, AutoCloseable {
/**
* Override: AutoClosable.close() throws Exception.
*/
public abstract void close();
protected Cursor cursor;
public abstract int getPosition();
public AutoCloseableIterator(Cursor cursor) {
this.cursor = cursor;
}
public abstract boolean moveToPosition(int position);
@Override
@NonNull
public final T next() {
if (cursor == null || !cursor.moveToNext()) {
throw new NoSuchElementException();
}
return get();
}
public final int getPosition() {
return cursor.getPosition();
}
public final boolean moveToPosition(int position) {
return cursor.moveToPosition(position);
}
@Override
public final boolean hasNext() {
if (cursor == null) {
return false;
}
return !cursor.isLast() && !cursor.isAfterLast();
}
@NonNull
public abstract T get();
@NonNull
public T get(int position) {
public final T get(int position) {
moveToPosition(position);
return get();
}
public abstract int getCount();
@VisibleForTesting
public final int getCount() {
return cursor.getCount();
}
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
@Override
public final void close() {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
}