全部产品
云市场

java_lang_NullPointerException

更新时间:2018-04-19 20:40:03

问题分析:

试图对一个为null的对象执行成员函数、试图获取null对象的成员变量、试图获取null数组的长度、试图访问数组中某个空对象、抛出一个对象而实际未初始化为null时,此时会抛出NullPointerException异常。

解决方案:对可以预见为空的对象进行处理,对不可预知的对象判断是否是null,然后再访问内部成员变量或执行成员函数。

代码示例:

  1. 示例1:

    1. Exception in thread "main" java.lang.NullPointerException

解决方案:判断对象是否为null,不是null再执行对象成员函数。

  1. public String[] split(String content){
  2. if(content!=null){
  3. String[] result=content.split("\\s+");
  4. return result;
  5. }
  6. return null;
  7. }
  1. 示例2:

    1. java.lang.NullPointerException
    2. at android.webkit.WebViewClassic$WebViewInputConnection.setNewText(WebViewClassic.java:587)
    3. at android.webkit.WebViewClassic$WebViewInputConnection.setComposingText(WebViewClassic.java:327)
    4. at android.webkit.WebViewClassic$WebViewInputConnection.commitText(WebViewClassic.java:343)
    5. at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:279)
    6. at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
    7. at android.os.Handler.dispatchMessage(Handler.java:107)
    8. at android.os.Looper.loop(Looper.java:194)
    9. at android.app.ActivityThread.main(ActivityThread.java:5391)
    10. at java.lang.reflect.Method.invokeNative(Native Method)
    11. at java.lang.reflect.Method.invoke(Method.java:525)
    12. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
    13. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
    14. at dalvik.system.NativeStart.main(Native Method)

在使用Google Play Services的google-play-services.jar时报错,建议设置全局Exception Handler。

  1. public class MyApplication extends Application {
  2. @Override
  3. public void onCreate() {
  4. super.onCreate();
  5. Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  6. @Override
  7. public void uncaughtException(Thread thread, final Throwable ex) {
  8. // Custom code here to handle the error.
  9. }
  10. });
  11. }
  12. }

参考文献:

  1. https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html

  2. http://stackoverflow.com/questions/21866459/android-nullpointerexception-on-webview

  3. https://groups.google.com/forum/#!topic/google-admob-ads-sdk/QvUhH5ZGIHQ

  4. http://stackoverflow.com/questions/18824076/how-to-catch-this-exception-in-android-webview