错误LOG:
E/AndroidRuntime(16635): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skyworth.system_monitor/com.skyworth.system_monitor.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(16635): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
E/AndroidRuntime(16635): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(16635): at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(16635): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(16635): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(16635): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(16635): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(16635): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(16635): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(16635): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:937)
E/AndroidRuntime(16635): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:753)
E/AndroidRuntime(16635): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(16635): Caused by: java.lang.NullPointerException
E/AndroidRuntime(16635): at com.skyworth.sm.content.MemeryInfo.getDirSize(MemeryInfo.java:64)
E/AndroidRuntime(16635): at com.skyworth.sm.content.MemeryInfo.getDirSizelist(MemeryInfo.java:49)
E/AndroidRuntime(16635): at com.skyworth.sm.content.MemeryInfo.getDataSpace(MemeryInfo.java:33)
E/AndroidRuntime(16635): at com.skyworth.system_monitor.MainActivity.onCreate(MainActivity.java:32)
E/AndroidRuntime(16635): at android.app.Activity.performCreate(Activity.java:5232)
E/AndroidRuntime(16635): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(16635): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
E/AndroidRuntime(16635): ... 11 more
W/ActivityManager( 1545): Force finishing activity com.skyworth.system_monitor/.MainActivity
产生的原因:
因为文件夹(file)为空,所以file.list()会返回null,然后调用.length获取数组长度,其实是null.length,所以抛出空指针异常,这种异常在Android中会抛出,但是在Java程序中不会出现,这是Android与纯Java程序的一个不同点。
解决办法:用file.list() == null判断文件夹是否为空。