Adibe7 Adibe7 - 2 years ago 922
Java Question

How to use assert in android?

I want to use

assert obj != null : "object cannot be null"
on Android device. The assert doesn't seem to work, so i searched online and i found this local solution:


adb shell setprop debug.assert 1


it does work on my local machine.

I want to run this command using my eclipse project(so it would be in the source control).
How do i do it?

Thanks!

Answer Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download