Android - Correct usage of Cursor
I've seen many Android source code examples on how to loop through a Cursor and most of them are unnecessarily complicated or perform unnecessary operations.
Sincerely, I don't know why people overcomplicate it. Cursor usage is pretty simple and similar to JDBC's ResultSet. The general code skeleton is as follows:
There's no need to check if Cursor instance is null (Android API never returns a null Cursor) or moving to first (moveToFirst()) and do/while because returned Cursors are always positioned before first element. And don't forget to close the Cursor on a finally to ensure it is closed even if an exception is thrown (to avoid memory leaks).
KISS!
Sincerely, I don't know why people overcomplicate it. Cursor usage is pretty simple and similar to JDBC's ResultSet. The general code skeleton is as follows:
Cursor c = null;
try { c = ... // Get the Cursor from SQLite DB while (c.moveToNext()) { // Perform operations with current row data } } finally { if (c != null) { c.close(); } }
There's no need to check if Cursor instance is null (Android API never returns a null Cursor) or moving to first (moveToFirst()) and do/while because returned Cursors are always positioned before first element. And don't forget to close the Cursor on a finally to ensure it is closed even if an exception is thrown (to avoid memory leaks).
KISS!
Comments
Post a Comment
Comment, motherf*cker