0

我在以下 2 行中一直收到一个错误空指针,我不知道如何纠正它。

NodeList textList = NameElement.getChildNodes();
String name = ((Node)textList.item(0)).getNodeValue().trim();




   import java.io.FileInputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;

public class PlayActivity extends Activity {
    private Spinner spntreasure;
    private static final String FILENAME = "data.xml";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play_activity);
        ImageButton cancelBtn =  (ImageButton)findViewById(R.id.cancelBtn1);

        addItemsOnspnTreasure();

        cancelBtn.setOnClickListener(new View.OnClickListener() 
        {           
            @Override
            public void onClick(View v) 
            {
                finish();
            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.play_activity, menu);
        return true;
    }

    // add items into spinner dynamically
      public void addItemsOnspnTreasure() 
      {

          ArrayList<String> List = new ArrayList<String>();

          spntreasure = (Spinner) findViewById(R.id.spntreasure);

          try {
                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                FileInputStream fis = openFileInput(FILENAME);
                Document doc = docBuilder.parse(fis);
                fis.close();

                // normalize text representation
                doc.getDocumentElement ().normalize ();
                String myRoot = doc.getDocumentElement().getNodeName();

                NodeList listOfTreas = doc.getElementsByTagName("Treasure");
                int totalTreas = listOfTreas.getLength();
                int myTotalTreasure = totalTreas;

                for(int s=0; s<listOfTreas.getLength() ; s++){

                    Node firstTreasNode = listOfTreas.item(s);
                    if(firstTreasNode.getNodeType() == Node.ELEMENT_NODE)
                    {

                        Element firstTreasElement = (Element)firstTreasNode;

                        //-------
                        NodeList NameList = firstTreasElement.getElementsByTagName("Name");
                        Element NameElement = (Element)NameList.item(0);

                        NodeList textList = NameElement.getChildNodes();
                        String name = ((Node)textList.item(0)).getNodeValue().trim();

                        //-------
                        NodeList Clue1List = firstTreasElement.getElementsByTagName("Clue1");
                        Element Clue1Element = (Element)Clue1List.item(0);

                        NodeList textLNList = Clue1Element.getChildNodes();
                        String clue1 =((Node)textLNList.item(0)).getNodeValue().trim();

                        //----
                        NodeList Clue2List = firstTreasElement.getElementsByTagName("Clue2");
                        Element Clue2Element = (Element)Clue2List.item(0);

                        NodeList textClue2List = Clue2Element.getChildNodes();
                        String clue2 = ((Node)textClue2List.item(0)).getNodeValue().trim();

                        //------

                    }//end of if clause

                }//end of for loop with s var

          }catch (SAXParseException err) {
                System.out.println ("** Parsing error" + ", line " 
                     + err.getLineNumber () + ", uri " + err.getSystemId ());
                System.out.println(" " + err.getMessage ());

                }catch (SAXException e) {
                Exception x = e.getException ();
                ((x == null) ? e : x).printStackTrace ();

                }catch (Throwable t) {
                t.printStackTrace ();
                }


        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, List);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spntreasure.setAdapter(dataAdapter);
      }

}
4

2 回答 2

1

NameElement 在您的 XML 中没有子节点。如果您尝试访问 NameElement.getChildNodes(),它将返回 NULL,而 textList.item(0) 将导致 NullPointerException。

现在,我希望这个问题出现在 StackOverflow 上,这样我就可以获得一些代表。<_<

(这个答案是提问者发布他的 xml 代码的 G+ 帖子的延续)。

在第 88 行尝试这个,看看它是否有效,然后对 Clue 节点尝试同样的方法

String name = ((Element) NameList.item(0)).getAttribute("Name");

根据这份文件:http ://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html

当 Node 被强制转换为 Element 时, nodeValue 变为 null 因为没有明显的映射,或者我认为 Element 的 nodeValue 始终为 null (?) 是该文档试图说的。

于 2013-02-28T21:10:46.420 回答
0

您正在将 NodeList 转换为 Element:

NodeList fstNode = doc.getElementsByTagName("Name");
Element fstElmnt = (Element) fstNode;

这是错误的。尝试:

......
NodeList fstNode = doc.getElementsByTagName("Name");
int size = fstNode.getLength();
for(int i=0; i< size; i++){
   Node curr= nodeList.item(i);
   if (curr.getNodeType() == Node.ELEMENT_NODE) {
       Element elem = (Element) curr;
       .... 
   }
   ......
}
.......
于 2013-02-27T21:29:04.440 回答