今天遇到个蛋痛的问题,明明APK的layout文件中有对应的TextView的id,但运行的时候总是报错如下:
E/AndroidRuntime( 4044): FATAL EXCEPTION: main
E/AndroidRuntime( 4044): Process: com.actions.pcbatest, PID: 4044
E/AndroidRuntime( 4044): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.actions.pcbatest/com.actions.pcbatest.PcbaTestActivity}: java
ng.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
E/AndroidRuntime( 4044): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
E/AndroidRuntime( 4044): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
E/AndroidRuntime( 4044): at android.app.ActivityThread.access$800(ActivityThread.java:151)
E/AndroidRuntime( 4044): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
E/AndroidRuntime( 4044): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime( 4044): at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime( 4044): at android.app.ActivityThread.main(ActivityThread.java:5258)
E/AndroidRuntime( 4044): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 4044): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 4044): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
E/AndroidRuntime( 4044): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
E/AndroidRuntime( 4044): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequ
e)' on a null object reference
E/AndroidRuntime( 4044): at com.actions.pcbatest.PcbaTestActivity.initialize(PcbaTestActivity.java:388) //这一行的findViewById报错
E/AndroidRuntime( 4044): at com.actions.pcbatest.PcbaTestActivity.onCreate(PcbaTestActivity.java:286)
E/AndroidRuntime( 4044): at android.app.Activity.performCreate(Activity.java:6006)
E/AndroidRuntime( 4044): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1116)
E/AndroidRuntime( 4044): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
E/AndroidRuntime( 4044): ... 10 more
W/ActivityManager( 416): Force finishing activity 1 com.actions.pcbatest/.PcbaTestActivity
调试了很久,百思不得其解,后来发现是不同的设备的分辨率不同匹配了不同的layout文件导致的。
layout目录结构如下:
| |~layout-w1024dp-mdpi/
| | `-main.xml*
| |~layout-w1280dp-mdpi/
| | `-main.xml*
| |~layout-w800dp-mdpi/
| | `-main.xml*
| |~layout/
| | `-main.xml*
因为明明在VR设备上运行正常,但是安装到平板上就是报错,原来是匹配了下面这个:
| |~layout-w1280dp-mdpi/
| | `-main.xml*
而我添加的TextView只是在下面layout中:
| |~layout/
| | `-main.xml*
所以造成了这个bug。
解决方案就是:往不同的分辨率的xml中都添加进该id的TextView即可解决问题。