24

Android Lint complain about assert() being used, and recommend using BuildConfig.DEBUG conditional checks instead.

I understood perfectly why assert are not safe to use on android, but what exactly are "BuildConfig.DEBUG conditional checks" ?

How would the following example code be amended ?

Context ctx = getContext();
assert (ctx instanceof FragmentActivity);
fragment_manager = ((FragmentActivity) ctx).getSupportFragmentManager();

1 Answer 1

27

I think what lint is trying to say is that add a check of BuildConfig.DEBUG for assert statement

if(BuildConfig.DEBUG)

assert (ctx instanceof FragmentActivity);

so that assert works only when you are testing the app, but on release versions assert will not be called

BuildConfig.DEBUG will be false when you export a release build.

Edit: Looks like you should do something like below rather than using assert

 if(BuildConfig.DEBUG && !(ctx instanceof FragmentActivity))
      throw new RuntimeException();

instead of assert.

source: http://tools.android.com/recent/androidstudio045released

Some new lint checks, and in particular one which flags uses of the assertion keyword. This does not work reliably on devices and you should use BuildConfig.DEBUG to do conditional checks instead.

6
  • 1
    But assert() code is not called/not completely implemented on dalvik, so even when running a test (on an emulator), assert() should not be used.
    – Rémi
    Apr 16, 2014 at 15:47
  • 1
    AFAIK, assert can be enabled using debug.assert =1 system prop
    – nandeesh
    Apr 16, 2014 at 15:50
  • 1
    According to this post code.google.com/p/android/issues/detail?id=65183 "[assert()] was never supported in Dalvik. The system property exists, but is pretty much ignored in various places. There is a reason that this isn't documented or made easy to use."
    – Rémi
    Apr 16, 2014 at 15:55
  • I'm finding that BuildConfig.DEBUG is true when pressing the "bug" play button in Android Studio, or the regular play button. So I'm seeing asserts triggered when I'm actually not "debugging". Feb 6, 2015 at 19:50
  • 1
    maybe instead of RuntimeException, you want to use AssertionError
    – hoijui
    Mar 14, 2018 at 23:33

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.