SAX-разбор создает исключение нулевого указателя - PullRequest
1 голос
/ 19 марта 2012

Я получаю 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-карту надлежащим образом, но не анализируется.

1 Ответ

0 голосов
/ 19 марта 2012

SAX (Simple API for XML) - это API анализатора последовательного доступа на основе событий, разработанный списком рассылки XML-DEV для документов XML. SAX предоставляет механизм для чтения данных из XML-документа, который является альтернативой тому, который предоставляется объектной моделью документа (DOM). Там, где DOM работает с документом в целом, парсеры SAX работают с каждым фрагментом XML-документа последовательно

Пожалуйста, обратитесь по этой ссылке для вашего решения.

Это тебе поможет.

...