Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to delete rows from Android SQLite database while iterating cursor

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.

like image 324
RTF Avatar asked Jan 12 '23 13:01

RTF


1 Answers

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).

like image 104
CommonsWare Avatar answered Jan 14 '23 03:01

CommonsWare