【问题标题】:SAX parsing produces a null pointer exceptionSAX 解析产生空指针异常
【发布时间】:2012-03-19 08:56:06
【问题描述】:

我从服务器检索 XML,将其保存到 SD 卡中,然后解析该 XML。我得到了这个例外:

03-19 13:53:26.943: E/AndroidRuntime(12512): FATAL EXCEPTION: main
03-19 13:53:26.943: E/AndroidRuntime(12512): java.lang.NullPointerException.

我正在使用此代码:

/** Create Object For SiteList Class */
SitesList sitesList = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    DownloadFromUrl("http://www.androidpeople.com/wp- content/uploads/2010/06/example.xml","example.xml");
    /** Create a new layout to display the view */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(1);
    /** Create a new textview array to display the results */
    TextView name[];
    TextView website[];
    TextView category[];
    try {
        /** Handling XML */
        String path = Environment.getExternalStorageDirectory() +"../xmls"+"/example.xml";
        File file = new File(path);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        DataHandler myXMLHandler = new DataHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(new InputStreamReader(new    FileInputStream(file))));//parse(new InputSource(sourceUrl.openStream()));
    } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
    }
    /** Get result from DataHandler SitlesList Object */
    sitesList = DataHandler.sitesList;
    /** Assign textview array lenght by arraylist size */
    name = new TextView[sitesList.getName().size()];
    website = new TextView[sitesList.getWebsite().size()];
    category = new TextView[sitesList.getCategory().size()];
    /** Set the result text in textview and add it to layout */
    for (int i = 0; i < sitesList.getName().size(); i++) {
        name[i] = new TextView(this);
        name[i].setText("Name = "+sitesList.getName().get(i));
        website[i] = new TextView(this);
        website[i].setText("Website = "+sitesList.getWebsite().get(i));
        category[i] = new TextView(this);
        category[i].setText("Website Category = "+sitesList.getCategory().get(i));
        layout.addView(name[i]);
        layout.addView(website[i]);
        layout.addView(category[i]);
    }
    /** Set the layout view to display */
    setContentView(layout);
}

private void DownloadFromUrl(String DownloadUrl, String fileName)
{
    URL url;
    File root = android.os.Environment.getExternalStorageDirectory();
    File dir = new File (root.getAbsolutePath() + "/xmls");
    if(dir.exists()==false) {
        dir.mkdirs();
    }
    try {
        url = new URL(DownloadUrl);
        File file = new File(dir, fileName);
        Log.d("DownloadManager", "download begining");
        Log.d("DownloadManager", "download url:" + url);
        Log.d("DownloadManager", "downloaded file name:" + fileName);
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();
        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        //Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } //you can write here any link
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我的处理程序类是:

Boolean currentElement = false;
Context theContext;
String currentValue = null;
public static SitesList sitesList = null;

public static SitesList getSitesList()
{
    return sitesList;
}

public static void setSitesList(SitesList sitesList)
{
    DataHandler.sitesList = sitesList;
}

@Override
public void startElement(String uri, String localName, String qName,
                         Attributes attributes) throws SAXException
{
    super.startElement(uri, localName, qName, attributes);
    currentElement = true;
    if (localName.equals("maintag"))
    {
        /** Start */
        sitesList = new SitesList();
    }
    else if (localName.equals("website"))
    {
        /** Get attribute value */
        String attr = attributes.getValue("category");
        sitesList.setCategory(attr);
    }
}

@Override
public void endElement(String uri, String localName, String qName)
    throws SAXException {
    super.endElement(uri, localName, qName);
    currentElement = false;
    /** set value */
    if (localName.equalsIgnoreCase("name"))
        sitesList.setName(currentValue);
    else if (localName.equalsIgnoreCase("website"))
        sitesList.setWebsite(currentValue);
}

@Override
public void characters(char[] ch, int start, int length)
    throws SAXException {
// TODO Auto-generated method stub
    super.characters(ch, start, length);
    if (currentElement)
    {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }
}

我的列表类是:

/** Variables */
private ArrayList name = new ArrayList();
private ArrayList website = new ArrayList();
private ArrayList category = new ArrayList();

/** In Setter method default it will return arraylist
 * change that to add */
public ArrayList getName() {
    return name;
}
public void setName(String name) {
    this.name.add(name);
}

public ArrayList getWebsite() {
    return website;
}
public void setWebsite(String website) {
    this.website.add(website);
}

public ArrayList getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category.add(category);
}

XML 文件已正确下载并保存到 SD 卡中,但未解析。

【问题讨论】:

  • 发生异常时,总是把完整的logcat放在这里......
  • 我只能修复它先生..发生问题。我可以修复它“../xmls”删除“..”它正在工作..
  • 我知道每个人都在这里寻求解决方案,但我不知道什么 prblm 那么谁能解决它>

标签: android xml sax


【解决方案1】:

SAX (Simple API for XML) 是由 XML-DEV 邮件列表为 XML 文档开发的基于事件的顺序访问解析器 API。 SAX 提供了一种从 XML 文档中读取数据的机制,它可以替代文档对象模型 (DOM) 提供的机制。 DOM 对整个文档进行操作,而 SAX 解析器则按顺序对 XML 文档的每个部分进行操作

请参考此link 以获得您的解决方案。

它会帮助你。

【讨论】:

猜你喜欢
  • 2012-02-04
  • 2014-01-18
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 2019-03-31
  • 2013-01-15
  • 2012-03-30
  • 1970-01-01
相关资源
最近更新 更多