9 July 2012

How to solve problem NoSuchMethodError for Sensor.getMinDelay() ?

you wrote a awesome app that using sensor and method getMindDelay() ,but when you test on various devices ,then you notices that .... on some devices,it crashes and on some not.
You see error which looks more less like that:

java.lang.NoSuchMethodError: android.hardware.Sensor.getMinDelay
 at dms.pastor.diagnostictools.activities.diags.ProximitySensor.doMagic() at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2803)
at android.app.ActivityThread.access$2300(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2136)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

Problem:

This method is supported from SDK 9(Android 2.3) and above,so if you run app in Android 2.2 ,then you will see above exception.

Solution:
Use if else statement using  Build.VERSION.SDK_INT

if(Build.VERSION.SDK_INT >= 9) {
  minDelayValue =  String.valueOf(epicSensor.getMinDelay());
}else{
  minDelayValue =  "You are using an ancient Android ,LOL";
  }

Source:
http://developer.android.com/reference/android/hardware/Sensor.html#getMinDelay()