3

It is possibly duplicate for Question1 or Question2, but for me its still not clear. They say, try-with-resources supported from 19 api only, but refer to that question its not so.

I have tested by my own with Realm.

boolean isClosed = RealmManager.isClosed(); //false here
try (Realm realm = RealmManager.getRealm()) {
     realm.executeTransaction(r -> r.where(User.class).findAll());
} catch (Exception ex) {
     ex.printStackTrace();
}
isClosed = RealmManager.isClosed(); //true here

public static boolean isClosed() {
    return realm == null || realm.isClosed();
}

And its works fine on 22 api (real phone) and 16 api (emulator). So will that block work fine on pre 19 api on most phones and where is a truth?

I use Retrolabmda.

Gradle configuration:

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
TooLazy
  • 836
  • 4
  • 11
  • 29

1 Answers1

2

You can use try-with-resources at all API level using Android Studio 3.0:

Android Studio 3.0 Preview 1 and later extends support for try-with-resources to all Android API levels.

Also, you need to add annotation @SuppressLint("NewApi") to code block to hide warnings if you build your application for API level < 19. In case of this annotation is not applicable, you however can ignore warnings, build and run your application even if try-with-resources code block is highlighted as error.

Sergei Bubenshchikov
  • 5,275
  • 3
  • 33
  • 60