i am Roger Li

開發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 null in a case where an object is required. These include:

    • Calling the instance method of a null object.
    • Accessing or modifying the field of a null object.
    • Taking the length of null as if it were an array.
    • Accessing or modifying the slots of null as if it were an array.
    • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects 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("'", "''")

喜歡這篇文章嗎? 加我到你 Google+Follow @iamrogerli吧!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *