How to use assert in android?
Create your own assert method:
public static <T> T assertNotNull(T object) {
if (object == null)
throw new AssertionError("Object cannot be null");
return object;
}
Returning same object allows for using this in assignments for brevity.
Assert won't work in Android because most of the time a person isn't running in debug mode, but rather some optimized code. Thus, the proper solution is to manually throw an exception, with code like this:
if (obj==null) throw new AssertionError("Object cannot be null");
It should be noted that by design, Asserts are intended for debug code, and not for release time code. So this might not be the best use of throwing an Assert. But this is how you can do it still, so...
Tested on Android 4.x device, it is possible to use Java assert on Android device:
- Edit /system/build.prop (for example by X-plore), add line at end of file: debug.assert=1
- Reboot phone
Now your Android device is sensible to assert checks, and will throw AssertionError when assert check fails.
EDIT:
Another easy approach, enabling asserts from PC until device is restarted:
platform-tools\adb shell setprop debug.assert 1
You may for example create a .bat file (on Windows) and run it when device is attached.
if (somevar == null) throw new RuntimeException();
Replace RuntimeException() with an appropriate exception subtype.