Android解析错误 - ClassCastException - 集合$ EmptyList

时间:2013-02-27 20:52:43

标签: android xml-parsing

我保持在以下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);
      }

}

2 个答案:

答案 0 :(得分:1)

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

现在,我希望这个问题在StackOverflow上,所以我可以得到一些代表。 &LT; _&LT;

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

在第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(?)是该文档试图说的。

答案 1 :(得分: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;
       .... 
   }
   ......
}
.......