null pointer exception using SAX XML Parser - java

I am using the SAX Parser for XML Parsing. The problem is if I print, everything is fine. However, If I want to save anything, I get this error message (with the typos):
"XML Pasing Excpetion = java.lang.NullPointerException"
My code is given below:
Parser code:
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://50.19.125.224/Demo/VeryGoodSex_and_the_City_S6E6.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler((ContentHandler) myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
Object to hold XML parsed Info:
public class ParserObject {
String name=null;
String description=null;
String bitly=null; //single
String productLink=null;//single
String productPrice=null;//single
Vector<String> price=null;
}
Handler class:
static ParserObject[] xmlDataObject = null;
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (qName.equalsIgnoreCase("title"))
{
xmlDataObject[index].name=currentValue;
}
else if (qName.equalsIgnoreCase("artist"))
{
xmlDataObject[index].artist=currentValue;
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (qName.equalsIgnoreCase("allinfo"))
{
System.out.println("started");
}
else if (qName.equalsIgnoreCase("tags"))
{
insideTag=1;
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}

Your ParserObject array i.e xmlDataObject is having null value thats is why it is showing null pointer exception. This is my View and it might be wrong but once check it too.

Related

Turn java XML SAX Parser to web app Tomcat

I've got a java SAX Parser for XML (we set the date, make URL reqest for this date and parse XML file). Now I need to turn this code to web app in Tomcat. I've imported all nessessary libraries, created artefacts, but don't know how to change code itself.\
Here is initial code
Handler:
public class UserHandler extends DefaultHandler {
boolean bName = false;
boolean bValue = false;
String result=" ";
#Override
public void startElement(String uri,
String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("Valute")) {
String CharCode = attributes.getValue("CharCode");
} else if (qName.equalsIgnoreCase("Name")) {
bName = true;
} else if (qName.equalsIgnoreCase("Value")) {
bValue = true;
}
}
#Override
public void endElement(String uri,
String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("Valute")) {
System.out.print(" ");
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bName) {
result=(new String(ch, start, length)+" ");
bName = false;
} else if (bValue) {
result=result+(new String(ch, start, length));
bValue = false;
System.out.print(result);
}
}
}
Main:
public static void main(String[] args) throws MalformedURLException {
//Set the date dd.mm.yyyy
String date="12.08.2020";
String link ="http://www.cbr.ru/scripts/XML_daily.asp?date_req=";
URL url =new URL(link);
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
UserHandler userHandler = new UserHandler();
saxParser.parse(String.valueOf(url+date), userHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Java SAX is not parsing properly

I would appreciate any help on this.
This is my first handler I wrote.
I got I REST Webservice returning XML of links. It has quite simple structure and is not deep.
I wrote a handler for this:
public class SAXHandlerLnk extends DefaultHandler {
public List<Link> lnkList = new ArrayList();
Link lnk = null;
private StringBuilder content = new StringBuilder();
#Override
//Triggered when the start of tag is found.
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("link")) {
lnk = new Link();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("link")) {
lnkList.add(lnk);
}
else if (qName.equals("applicationCode")) {
lnk.applicationCode = content.toString();
}
else if (qName.equals("moduleCode")) {
lnk.moduleCode = content.toString();
}
else if (qName.equals("linkCode")) {
lnk.linkCode = content.toString();
}
else if (qName.equals("languageCode")) {
lnk.languageCode = content.toString();
}
else if (qName.equals("value")) {
lnk.value = content.toString();
}
else if (qName.equals("illustrationUrl")) {
lnk.illustrationUrl = content.toString();
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
content.append(ch, start, length);
}
}
Some XML returned can be empty eg. or . When this happens my handler unfortunatelly adds previous value to the Object lnk. So when is empty in XML, I got lnk.illustrationUrl = content; equal to lnk.value.
Link{applicationCode='onedownload', moduleCode='onedownload',...}
In the above example, I would like moduleCode to be empty or null, because in XML it is an empty tag.
Here is the calling class:
public class XMLRepositoryRestLinksFilterSAXParser {
public static void main(String[] args) throws Exception {
SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandlerLnk handler = new SAXHandlerLnk();
parser.parse({URL}, handler);
for ( Link lnk : handler.lnkList){
System.out.println(lnk);
}
}
}
Like stated in my comment, you'd do the following. The callbacks are usually called in startElement, characters, (nested?), characters, endElement order, where (nested?) represents an optional repeat of the entire sequence.
#Override
//Triggered when the start of tag is found.
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
content = null;
if (qName.equals("link")) {
lnk = new Link();
}
}
Note that characters may be called multiple times per a single XML element in your document, so your current code might fail to capture all content. You'd be better off using a StringBuilder instead of a String object to hold your character content and append to it. See this answer for an example.

not able to add data while parsing xml data using SAXParser

I am tryin to get rss feed using xml parsing and
I am getting problem while parsing xml data using SAXParser
I have tried something like
In my MainActivity.java
try{
/****** Creating a new instance of the SAX parser ****************/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxParser = saxPF.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
URL url = new URL("http://ibnlive.in.com/ibnrss/rss/world/world.xml");
myXMLHandler = new FeedsXMLHandler();
xmlReader.setContentHandler(myXMLHandler);
xmlReader.parse(new InputSource(url.openStream()));
}catch (Exception e) {
e.printStackTrace();
}
I am retriving data from my handler using
ArrayList<FeedsItems> feedsData = myXMLHandler.getXMLData();
Log.v("size",Integer.toString(feedsData.size()));
Here its showing size as zero.
My FeedsXMLHandler.java
private ArrayList<FeedsItems> dataArray = new ArrayList<FeedsItems>();
private FeedsItems data = null;
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
{
elementValue = "";
elementOn = true;
if (localName.equalsIgnoreCase("rss"))
{
// data = new FeedsItems();
}
else if (localName.equalsIgnoreCase("item"))
{
data = new FeedsItems();
Log.v("Item","I am in item block");
}
else if (localName.equalsIgnoreCase("description"))
{
bufferDesc = new StringBuilder();
elementOn = true;
}
else if (localName.equalsIgnoreCase("title"))
{
bufferTitle = new StringBuilder();
elementOn = true;
}
else if(localName.equalsIgnoreCase("link"))
{
bufferLink = new StringBuilder();
elementOn = true;
}
}
/*********** Method will be called when the tags of the XML end **************/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/*** Sets the values after retrieving the values from the XML tags ******/
if (localName.equalsIgnoreCase("title"))
{
elementOn = false;
data.setTitle(bufferTitle.toString());
bufferTitle.delete(0,bufferTitle.length());
}
else if (localName.equalsIgnoreCase("link")){
elementOn = false;
data.setFeedsUrl(bufferLink.toString());
bufferLink.delete(0,bufferLink.length());
}
else if (localName.equalsIgnoreCase("description")){
elementOn = false;
data.setDescription(bufferDesc.toString());
bufferDesc.delete(0, bufferDesc.length());
}
else if (localName.equalsIgnoreCase("item")){
dataArray.add(data);
}
}
I am not able to understand whats wrong in it. I have already implemented xml parsing using SAXParser in this method. Any help or suggestion will be welcome

XML response how to assign values to variables

I get the xml repsonse for http request. I store it as a string variable
String str = in.readLine();
And the contents of str is:
<response>
<lastUpdate>2012-04-26 21:29:18</lastUpdate>
<state>tx</state>
<population>
<li>
<timeWindow>DAYS7</timeWindow>
<confidenceInterval>
<high>15</high>
<low>0</low>
</confidenceInterval>
<size>0</size>
</li>
</population>
</response>
I want to assign tx, DAYS7 to variables. How do I do that?
Thanks
Slightly modified code from http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
public class ReadXMLFile {
// Your variables
static String state;
static String timeWindow;
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
// Http Response you get
String httpResponse = "<response><lastUpdate>2012-04-26 21:29:18</lastUpdate><state>tx</state><population><li><timeWindow>DAYS7</timeWindow><confidenceInterval><high>15</high><low>0</low></confidenceInterval><size>0</size></li></population></response>";
DefaultHandler handler = new DefaultHandler() {
boolean bstate = false;
boolean tw = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("STATE")) {
bstate = true;
}
if (qName.equalsIgnoreCase("TIMEWINDOW")) {
tw = true;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bstate) {
state = new String(ch, start, length);
bstate = false;
}
if (tw) {
timeWindow = new String(ch, start, length);
tw = false;
}
}
};
saxParser.parse(new InputSource(new ByteArrayInputStream(httpResponse.getBytes("utf-8"))), handler);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("State is " + state);
System.out.println("Time windows is " + timeWindow);
}
}
If you're running this as a part of some process you might want to extend the ReadXMLFile from DefaultHandler.

Sax parser issues in android

I'm trying to parse a xml using SAX parser. The code works fine on pc but on android the elements doesn't get added to list .
In the code i'm trying to add the data within the tags sunrise & sunset onto the list array
In public
void endElement(..) {}
System.out.println("size of list " + timeLst.size()); //Always shows 0 in android
Below is the code..
TimeServiceParser tsp = new TimeServiceParser();
tsp.parseDocument(new URL("http://www.earthtools.org/sun/47.566667/-52.716667/14/3/99/1"));
tsp.printData();
public class TimeService extends DefaultHandler {
public void parseDocument(URL sourceUrl) {
SAXParserFactory spf = SAXParserFactory.newInstance();
try{
SAXParser sp = spf.newSAXParser();
InputStream is = sourceUrl.openStream();
sp.parse(is, this);
}catch(SAXException se) {
...
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
tempVal = "";
if(qName.equalsIgnoreCase("sunrise")) {
tempTimeData = new TimeData();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("sunrise")) {
tempTimeData.setSunriseTime(tempVal);
timeLst.add(tempTimeData);
}else if(qName.equalsIgnoreCase("sunset")) {
if(tempTimeData!=null) {
TimeData t = (TimeData)(timeLst.get(0));
t.setSunsetTime(tempVal);
}
}
System.out.println("size of list " + timeLst.size()); //Always shows 0 in android
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch , start , length);
}
public void printData() {
Iterator<TimeData> it = timeLst.listIterator();
while(it.hasNext()) {
TimeData td = (TimeData)(it.next());
System.out.println(td.getSunriseTime());
System.out.println(td.getSunsetTime());
}
}
}

Categories