LoginSignup
0
0

More than 5 years have passed since last update.

Cursor の close 処理に Java7 の try-with-resources 文を使う

Last updated at Posted at 2018-12-08

概要

Java7 で追加された try-with-resources 文を使って、データベースから値を取得する時に使う Cursor を close する処理を簡潔に書く方法を紹介します。

try-with-resources 文を使うコード

try (Cursor c = contentResolver.query(uri, projection, selection, selectionArgs, null)) {
    ... // (cursor を使う処理)
}

Content Provider からデータを取得するためのコードを try-with-resources 文 を使って書くと、上のようなコードになると思います。

try-with-resources 文では try の内側のブロックを抜ける時に自動的に Cursor#close() メソッドを呼び出すため、
明示的に close() を呼ぶ必要がなくなります。

try-with-resources 文を使わないとどうなるか

try-with-resources 文を使わずに、try-finally 文でコードを書くと以下のようになります。

Cursor c = contentResolver.query(uri, projection, selection, selectionArgs, null);
try {
    ... // (cursor を使う処理)
} finally {
    if (c != null) {
        c.close()
    }
}

finally 節を書く分コードが長くなります。
また、cursor が null でないことをチェックしてから close しなくてはならないので、
その分コードが長くなる上、null判定を忘れてNPEを起こす危険性もあります。

try-with-resources 文を使わない他の例として、以下のように try 文すら使わないコードがあります。

Cursor c = contentResolver.query(uri, projection, selection, selectionArgs, null);
... // (cursor を使う処理) ★
if (c != null) {
    c.close()
}

この書き方には、もし★の箇所で例外が発生すると cursor が close されないという問題があります。
そのため、避けたほうがよいでしょう。

まとめ

cursor を使うときは、try-with-resources 文で書くべきだと思います。
面倒な処理は気にする必要なく、簡潔なコードになりそうです。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0