For example:
public void removeStaleMovies(Set<String> updatedMovieList) {
Cursor cur = this.getReadableDatabase().rawQuery("SELECT id, title, year FROM movie", null);
cur.moveToFirst();
while (!cur.isAfterLast()) {
String title = cur.getString(1);
String year = cur.getString(2);
if (!updatedMovieList.contains(title + "-" + year)) {
// delete the row where 'id' = cur.getString(0)
// OR, delete the row using the object at the cursor's current position, if that's possible
// OR, if deletion isn't safe while iterating, build up a list of row id's and run a DELETE statement after iteration is finished
}
}
}
Is deletion safe to do? Or can it result in some unpredictable behavior? I am aware of this similar question, but I'm still unsure.
From a code safety standpoint, this should be OK, assuming that the result set of your query is less than 1MB. In that case, the Cursor
holds in heap space the entire result set, so it is insulated from any changes to the underlying database.
That being said, you may want to build up a list of rows to delete, simply so you can delete them in a single statement, rather than a bunch of individual statements (though wrapping those individual statements in a transaction may give you similar performance characteristics).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With