昨天在测试获取手机SD卡中所有图片中报ImageSwitcher空指针错误,但是打印出来的ImageSwitcher 中有值,很奇怪,改了很久.总算找出原因了.下面是错误代码:
11-22 01:57:00.753: ERROR/AndroidRuntime(309): FATAL EXCEPTION: main11-22 01:57:00.753: ERROR/AndroidRuntime(309): java.lang.NullPointerException11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.widget.ImageSwitcher.setImageURI(ImageSwitcher.java:48)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at com.covics.gallery.HelloTakePhotoActivity.onItemSelected(HelloTakePhotoActivity.java:113)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.widget.AdapterView.fireOnSelected(AdapterView.java:864)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.widget.AdapterView.access$200(AdapterView.java:42)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:830)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.os.Handler.handleCallback(Handler.java:587)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.os.Handler.dispatchMessage(Handler.java:92)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.os.Looper.loop(Looper.java:123)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at android.app.ActivityThread.main(ActivityThread.java:4627)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at java.lang.reflect.Method.invokeNative(Native Method)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at java.lang.reflect.Method.invoke(Method.java:521)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)11-22 01:57:00.753: ERROR/AndroidRuntime(309): at dalvik.system.NativeStart.main(Native Method)
他报的错误代码如下所示:
@Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { String url = listImages.get(position); System.out.println("url---->"+url); System.out.println("mImageSwitcher---->"+mImageSwitcher); System.out.println("uri---->"+Uri.parse(url)); mImageSwitcher.setImageURI(Uri.parse(url)); }
报空指针的是
mImageSwitcher.setImageURI(Uri.parse(url));
改了很久,都没弄出来,后来整体的再走了一遍流程,才发现错误所在:原来忘了为ImageSwitcher添加一个容器:
mImageSwitcher.setFactory(this);
悲剧啊,所以以后大家代码要写仔细些啊,要不改起来好无语啊...
等我把程序全部完成了,再发出来和大家一起分享.
最后提醒下,一定要为ImageSwitcher添加一个View.可以是ViewFactory也可以调用addView二次.