簡體   English   中英

解析XML Android給出了空指針異常

[英]Parsing xml android gives a null pointer exception

我正在解析以下XML:

<?xml version="1.0"?>
<Root>
    <ResponseCode>1</ResponseCode>
    <ResponseMessage>Login Successfull</ResponseMessage>
    <ResultSet>
        <User>
            <id>3</id>
            <username>hassan</username>
            <email>hassan</email>
            <password>abcd</password>
            <profileimagepath>c:/hahaha/hahaha</profileimagepath>
            <createdOn>2013-03-23 12:45:51</createdOn>
            <status>1</status>
        </User>
    </ResultSet>
</Root>

我用來解析XML的代碼是:

InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlResult));
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();

try {
    NodeList list = (NodeList) xPath.evaluate("/Root", is,XPathConstants.NODESET);
    for(int i=0; i<list.getLength(); i++){
        Node node = list.item(i);
        Element element = (Element) node;
        Log.d("VALUE OF NODE", element.getNodeValue());
    }
} catch (XPathExpressionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我無法判斷為什么會發生這種異常。 解析它的正確方法是什么? 我正在Android 4.0上執行此操作。 這是logcat

03-24 01:50:54.412: I/Post service Response(1097): <?xml version="1.0"?><Root><ResponseCode>1</ResponseCode><ResponseMessage>Login Successfull</ResponseMessage><ResultSet><User><id>3</id><username>hassan</username><email>hassan</email><password>abcd</password><profileimagepath>c:/hahaha/hahaha</profileimagepath><createdOn>2013-03-23 12:45:51</createdOn><status>1</status></User></ResultSet></Root>
03-24 01:50:54.804: D/dalvikvm(1097): GC_CONCURRENT freed 1940K, 21% free 7888K/9927K, paused 11ms+15ms
03-24 01:50:55.284: W/dalvikvm(1097): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
03-24 01:50:55.293: E/AndroidRuntime(1097): FATAL EXCEPTION: Thread-102
03-24 01:50:55.293: E/AndroidRuntime(1097): java.lang.NullPointerException: println needs a message
03-24 01:50:55.293: E/AndroidRuntime(1097):     at android.util.Log.println_native(Native Method)
03-24 01:50:55.293: E/AndroidRuntime(1097):     at android.util.Log.d(Log.java:138)
03-24 01:50:55.293: E/AndroidRuntime(1097):     at com.teamgreen.greenit.LoginActivity$1$1.run(LoginActivity.java:87)
03-24 01:51:28.253: I/Process(1097): Sending signal. PID: 1097 SIG: 9

您從Log.d()內部獲取異常,因為element.getNodeValue()返回null

您不能將null作為第二個參數提供給Log.d() 考慮將相應的行更改為:

Log.d("xml", "VALUE OF NODE: " + element.getNodeValue());

與其專注於特定問題,不如嘗試理解解釋堆棧跟蹤。 堆棧跟蹤指向確切的問題:

E / AndroidRuntime(1097):位於android.util.Log.d(Log.java:138)
E / AndroidRuntime(1097):at com.teamgreen.greenit.LoginActivity $ 1 $ 1.run(LoginActivity.java:87)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM