Problem description
NullPointerException occurs in the following cases: execute a member function on a null object, obtain the member variable of a null object, obtain the length of a null array, access an empty object in the array, and throw an object that is not initialized to null.
Solution
Check whether unpredictable objects are null before accessing internal member variables or executing member functions.
Sample code
Example 1
Exceptionin thread "main" java.lang.NullPointerExceptionCheck whether the object is null. If not, execute the member function.
publicString[] split(String content){
if(content!=null){
String[] result=content.split("\\s+");
return result;
}
returnnull;
}Example 2
java.lang.NullPointerException
at android.webkit.WebViewClassic$WebViewInputConnection.setNewText(WebViewClassic.java:587)
at android.webkit.WebViewClassic$WebViewInputConnection.setComposingText(WebViewClassic.java:327)
at android.webkit.WebViewClassic$WebViewInputConnection.commitText(WebViewClassic.java:343)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:279)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)This exception occurs when you use the google-play-services.jar file of Google Play Services. We recommend that you set a global exception handler.
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
// Custom code here to handle the error.
}
});
}
}References
https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
http://stackoverflow.com/questions/21866459/android-nullpointerexception-on-webview
https://groups.google.com/forum/#!topic/google-admob-ads-sdk/QvUhH5ZGIHQ
http://stackoverflow.com/questions/18824076/how-to-catch-this-exception-in-android-webview