So I have this piece of Java code:
if (e1.getNodeName().contains("column")) {
String temp_type = "";
String temp_index = "";
String name = "";
String format = "";
int index = 0;
DataType type = null;
try {
name = e1.getElementsByTagName("name").item(0).getTextContent();
System.out.println("Name: " + name);
} catch (NullPointerException e) {
System.out.println("No name");
}
try {
temp_index = e1.getAttributes().getNamedItem("index").getNodeValue();
index = Integer.parseInt(temp_index);
System.out.println("Index: " + index);
} catch (NullPointerException e) {
System.out.println("No index");
}
try {
temp_type = e1.getElementsByTagName("type").item(0).getTextContent();
try {
type= DataType.typeOf(temp_type);
} catch (UnknownDataTypeException e) {
System.out.println("Unknown Data Type");
}
System.out.println("Type: " + type);
} catch (NullPointerException e) {
System.out.println("No type");
}
try {
format = e1.getAttributes().getNamedItem("format").getNodeValue();
System.out.println("Format: " + format);
} catch (NullPointerException e) {
System.out.println("No format");
}
I am reading an XML file by implementing a DOM parser. I have a sample XML file and ever entry DOES NOT contain all of the following values (name is missing for the first entry). When I run this piece of code, everything prints out perfectly and I am able to handle the errors exactly how I want to.
My next step is to use each of these values (name, index, DataType, format) to create a Person object which I have defined in a previous class. I thus having the following piece of code to create a Person object and add it to an ArrayList (personList):
Person c = new Person(name, index, type, format);
personList.add(c);
Those two lines above give me a NullPointerException, even though I handle the thrown errors and I define initial values for my instance variables name, format, index and type at the beginning of the code.
Why doesn't Java see that I have already dealt with those errors and allow me to properly create a Person object?
I deeply appreciate all help.
Below is my Person class:
public class Person {
public String name;
public int index;
public DataType dataType;
public String dateFormat;
public Person(String name, int index, DataType dataType, String dateFormat) {
this.name = name;
this.index = index;
this.dataType = dataType;
this.dateFormat = dateFormat;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
public DataType getDataType() {
return dataType;
}
public String getDateFormat() {
return dateFormat;
}
enter code here
}