開發Android App 時經常遇到NullPointerException,今次配上replaceAll(),問題是...
開發Android App 時經常遇到NullPointerException ,不! 應該說是JAVA經常遇到。今次的問題/原因又是甚麼呢? 看看下面一句:
myArrayList.get(0).get("name").replaceAll("'", "''")
執行時所得到的error 如下:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.replaceAll(java.lang.String, java.lang.String)' on a null object reference
老掉牙的問題。NullPointerException 是指甚麼例外呢? 又引用Oracle Java 的Document:
public class NullPointerException
extends RuntimeException
Thrown when an application attempts to use
nullin a case where an object is required. These include:
- Calling the instance method of a
nullobject.
- Accessing or modifying the field of a
nullobject.
- Taking the length of
nullas if it were an array.
- Accessing or modifying the slots of
nullas if it were an array.
- Throwing
nullas if it were aThrowablevalue.
Applications should throw instances of this class to indicate other illegal uses of the
nullobject.NullPointerExceptionobjects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.
不作多除的翻譯了,我作出一個簡單的改動,NullPointerException 便會消失,固中原因你試試細心咀嚼一下吧:
(myArrayList.get(0).get("name")).replaceAll("'", "''")
喜歡這篇文章嗎? 加我到你
或 Follow @iamrogerli吧!