NullPointerException While Parsing XML

2019-09-11 13:32发布

问题:

I have followed the tutorial found here, and I am getting a NullPointerException. I've searched on StackOverflow and Google for a possible solution to this, but to no avail. Below you will see my code and my LogCat. Any ideas on what I should do to fix this?

XMLParsingExample.java (Line 57 = where the NullPointerException is occurring):

package com.androidpeople.xml.parsing;

import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class XMLParsingExample extends Activity {

    /** 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);

        /** 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 */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            /** Send URL to parse XML Tags */
            URL sourceUrl = new URL(
                    "http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");

            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            MyXMLHandler myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        /** Get result from MyXMLHandler SitlesList Object */
        sitesList = MyXMLHandler.sitesList;

        /** Assign textview array length by arraylist size */
        name = new TextView[sitesList.getName().size()];  //NullPointerException Here
        website = new TextView[sitesList.getName().size()];
        category = new TextView[sitesList.getName().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);
    }
}

MyXMLHandler.java:

package com.androidpeople.xml.parsing;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyXMLHandler extends DefaultHandler {

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

    public static SitesList getSitesList() {
        return sitesList;
    }

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

    /** Called when tag starts ( ex:- <name>AndroidPeople</name>
     * -- <name> )*/
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        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);
        }

    }

    /** Called when tag closing ( ex:- <name>AndroidPeople</name>
     * -- </name> )*/
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("name"))
            sitesList.setName(currentValue);
        else if (localName.equalsIgnoreCase("website"))
            sitesList.setWebsite(currentValue);

    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

}

SitesList.java:

package com.androidpeople.xml.parsing;

import java.util.ArrayList;

    /** Contains getter and setter method for varialbles */
    public class SitesList {

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

        /** In Setter method default it will return arraylist
         * change that to add */

        public ArrayList<String> getName() {
            return name;
        }

        public void setName(String name) {
            this.name.add(name);
        }

        public ArrayList<String> getWebsite() {
            return website;
        }

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

        public ArrayList<String> getCategory() {
            return category;
        }

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

}

AndroidParsing Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.androidpeople.xml.parsing"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".XMLParsingExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MyXMLHandler"></activity>
        <activity android:name=".SitesList"></activity>

    </application>

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

LogCat:

08-22 08:43:18.340: ERROR/AndroidRuntime(308): FATAL EXCEPTION: main
08-22 08:43:18.340: ERROR/AndroidRuntime(308): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidpeople.xml.parsing/com.androidpeople.xml.parsing.XMLParsingExample}: java.lang.NullPointerException
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.os.Looper.loop(Looper.java:123)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at java.lang.reflect.Method.invokeNative(Native Method)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at java.lang.reflect.Method.invoke(Method.java:521)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at dalvik.system.NativeStart.main(Native Method)
08-22 08:43:18.340: ERROR/AndroidRuntime(308): Caused by: java.lang.NullPointerException
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at com.androidpeople.xml.parsing.XMLParsingExample.onCreate(XMLParsingExample.java:57)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-22 08:43:18.340: ERROR/AndroidRuntime(308):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

回答1:

check this once. Here example is there. http://androidcodesnips.blogspot.com/2011/04/sax-parsing.html



回答2:

siteList is null in your handler. Trace your program to check whether or not you pass through the line :

    if (localName.equals("maintag"))
    {
        /** Start */
        sitesList = new SitesList();
    } 

Regards, Stéphane