I am writing an android application that parses an xml feed about car parks. I've created a separate class that receives an xml feed as a string, this class will then parse the string, creating objects for each car park found in the feed. I will use this each time I refresh the xml feed and need to parse it, should I make this class static or not. I am still not 100% sure on when to make something static or not.
My code:
public class XMLParser2 {
private static CarPark carPark;
private static ArrayList<CarPark> carParkListings;
// Parse XML string and save each car park object created within an Arraylist collection
public static ArrayList<CarPark> parseXML(String xml) throws XmlPullParserException, IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xml));
int eventType = xpp.getEventType();
carParkListings = new ArrayList<CarPark>();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("situation")) {
// Create new CarPark object to hold car park data
carPark = new CarPark();
}
// Check start tag for each element wanting to obtain and save in the
// carPark object using its associated set method
if (xpp.getName().equalsIgnoreCase("carparkstatus")) {
String status = xpp.nextText();
if (status.matches("enoughSpacesAvailable"))
carPark.setCarParkActive("Open");
else if (status.matches("carParkClosed"))
carPark.setCarParkActive("Closed");
else
carPark.setCarParkActive("Full");
}
if (xpp.getName().equalsIgnoreCase("overallstarttime")) {
carPark.setDateCreated(xpp.nextText());
}
if (xpp.getName().equalsIgnoreCase("latitude")) {
Double latitude = Double.parseDouble(xpp.nextText());
carPark.setLatitude(latitude);
}
if (xpp.getName().equalsIgnoreCase("longitude")) {
Double longitude = Double.parseDouble(xpp.nextText());
carPark.setLongtitude(longitude);
}
if (xpp.getName().equalsIgnoreCase("carparkidentity")) {
String[] identity = xpp.nextText().split("\\:");
carPark.setCarParkName(identity[0]);
carPark.setCarParkID(identity[1]);
}
if (xpp.getName().equalsIgnoreCase("occupiedspaces")) {
int occupiedSpaces = Integer.parseInt(xpp.nextText());
carPark.setOccupiedSpaces(occupiedSpaces);
}
if (xpp.getName().equalsIgnoreCase("totalcapacity")) {
int totalCapacity = Integer.parseInt(xpp.nextText());
carPark.setTotalSpaces(totalCapacity);
}
}
// Check if the tag is an end tag
else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equalsIgnoreCase("situation")) {
// Calculate total spaces free
carPark.setFreeSpaces();
// Add CarPark class object to carParkListings ArrayList collection
carParkListings.add(carPark);
}
}
// Move to next event
eventType = xpp.next();
}
// Return ArrayList collection
return carParkListings;
}
}