异常截获: NoClassDefFoundError——How to Include A Jar File
前几天遇到这样一个问题:
我明明引入了一个jar包,ctrul+单击也能进入源码,却总在new类的时候(如:User user = new User()),出现NoClassDefFoundError,无法实例化类。
控制台打印堆栈如下:
11-15 16:41:00.495: E/AndroidRuntime(7757): FATAL EXCEPTION: main11-15 16:41:00.495: E/AndroidRuntime(7757): java.lang.NoClassDefFoundError: com/google/zxing/integration/android/IntentIntegrator11-15 16:41:00.495: E/AndroidRuntime(7757): at com.google.zxing.client.androidtest.ZXingTestActivity$3.onClick(ZXingTestActivity.java:139)11-15 16:41:00.495: E/AndroidRuntime(7757): at android.view.View.performClick(View.java:4084)11-15 16:41:00.495: E/AndroidRuntime(7757): at android.view.View$PerformClick.run(View.java:16966)11-15 16:41:00.495: E/AndroidRuntime(7757): at android.os.Handler.handleCallback(Handler.java:615)11-15 16:41:00.495: E/AndroidRuntime(7757): at android.os.Handler.dispatchMessage(Handler.java:92)11-15 16:41:00.495: E/AndroidRuntime(7757): at android.os.Looper.loop(Looper.java:137)11-15 16:41:00.495: E/AndroidRuntime(7757): at android.app.ActivityThread.main(ActivityThread.java:4928)11-15 16:41:00.495: E/AndroidRuntime(7757): at java.lang.reflect.Method.invokeNative(Native Method)11-15 16:41:00.495: E/AndroidRuntime(7757): at java.lang.reflect.Method.invoke(Method.java:511)11-15 16:41:00.495: E/AndroidRuntime(7757): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)11-15 16:41:00.495: E/AndroidRuntime(7757): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)11-15 16:41:00.495: E/AndroidRuntime(7757): at dalvik.system.NativeStart.main(Native Method)11-15 16:41:00.495: E/AndroidRuntime(7757): Caused by: java.lang.ClassNotFoundException: com.google.zxing.integration.android.IntentIntegrator11-15 16:41:00.495: E/AndroidRuntime(7757): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)11-15 16:41:00.495: E/AndroidRuntime(7757): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)11-15 16:41:00.495: E/AndroidRuntime(7757): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)11-15 16:41:00.495: E/AndroidRuntime(7757): ... 12 more
可是,我明明引入了啊,也add到Build Path里面了,为什么还会报NoClassDefFoundError呢?
是我引入jar包的方法不对,放的位置不对,还是?
那么,如何引入一个jar文件呢(how to include a jar file)?
take the following steps, then you won't get the error:
1.Create a folder in the root of your project called libs.
2.Add the jar to that folder.
3.Right-click the jar and click to add to build path.
4.Clean your project.
5.Build project.
6.Run.
其实,在android project里面,在ADT的作用下,引入jar包,只需要将jar包拷入工程的libs目录下,不需要再add to build path,系统会自动将libs下的jar包添加到build path(实际上是添加到Android Dependencies这个library下)
哎,规范编程,“约定优于配置”,再也不会偷懒,把jar文件随便放了。