Reputation: 2749
I have followed multiple online tutorials on how to set up a SAX XML parser for the Android platform but none of them seem to work! Whats the problem? Heres my code:
Imports:
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.util.Log;
This Code is in a method that I know gets called, but why doesent logcat show "TESTING"?
try {
URL XMLURL = new URL("https://gdata.youtube.com/feeds/api/videos?q=Crystallize+Lindsey+Stirling+Offical+Music+Video&orderby=relevance");
SAXParserFactory SPF = SAXParserFactory.newInstance();
SAXParser SP = SPF.newSAXParser();
DefaultHandler mainHandler = new DefaultHandler(){
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if(localName.equals("Link")){
String possibleURL = attributes.getValue("href");
Log.i("TEST","TESTING");
}
}
};
SP.parse(new InputSource(XMLURL.openStream()),mainHandler);
} catch (Exception e) {
e.printStackTrace();
}
Thanks for any and all help!
Upvotes: 0
Views: 283
Reputation: 41127
This is a namespace issue.
SAXParserFactory SPF = SAXParserFactory.newInstance();
SAXParser SP = SPF.newSAXParser();
is giving you a parser that doesn't properly handle namespaces.
If you change the startElement to check qName
for the value "link", your code will work, but that's sort of a band-aid fix.
There are namespaces in this document, though this element is in the default namespace http://www.w3.org/2005/Atom specified for the document.
You should tell the parser factory to give you a namespace-aware parser:
SAXParserFactory SPF = SAXParserFactory.newInstance();
SPF.setNamespaceAware(true);
SAXParser SP = SPF.newSAXParser();
And then you'll get the expected result without changing the startElement
method, except you do have to look for the right value, i.e., check for "link" instead of "Link".
Upvotes: 1
Reputation: 366
Check your logcat for a big chunk of yellow text. It may inform you about any errors that crashed the SAX parser.
Upvotes: 0