I will show you how to use the ** try-with-resources ** statement added in Java7 to briefly write the process of closing the Cursor used when retrieving values from the database.
try (Cursor c = contentResolver.query(uri, projection, selection, selectionArgs, null)) {
... // (Processing using cursor)
}
If you write the code to get the data from the Content Provider using the try-with-resources statement, you'll get the code above.
Because the try-with-resources statement automatically calls the Cursor # close () method when exiting the block inside the try. You no longer have to explicitly call close ().
If you write the code in the try-finally statement without using the try-with-resources statement, it will be as follows.
Cursor c = contentResolver.query(uri, projection, selection, selectionArgs, null);
try {
... // (Processing using cursor)
} finally {
if (c != null) {
c.close()
}
}
The code becomes longer as the finally clause is written. Also, you have to check that cursor is not null before closing, so In addition to making the code longer, there is a risk of forgetting the null judgment and causing NPE.
Another example of not using the try-with-resources statement is code that doesn't even use the try statement:
Cursor c = contentResolver.query(uri, projection, selection, selectionArgs, null);
... // (Processing using cursor) ★
if (c != null) {
c.close()
}
The problem with this writing is that the cursor will not be closed if an exception occurs at the star. Therefore, it is better to avoid it.
When using cursor, I think you should write it in a try-with-resources statement. You don't have to worry about the tedious process, and it seems to be a concise code.
Recommended Posts