I have been trying to parse XML files using Asynctask, following [1] and [2] tutorials. I have implemented a class in my Activity as follows:
private class GetRoutes extends AsyncTask<String, Void, String[]> {
@Override
protected String[] doInBackground(String... urls) {
String[] read;
try{
RouteReader route = new RouteReader();
read = route.getRoutes();
} catch(IOException iox){
read = new String[1];
read[0] = getResources().getString(R.string.loading_error);
} catch(ArrayIndexOutOfBoundsException aiob){
read = new String[1];
read[0] = getResources().getString(R.string.loading_error);
} catch(NullPointerException npe){
read = new String[1];
read[0] = getResources().getString(R.string.loading_error);
}
return read;
}
@Override
protected void onPostExecute(String[] result) {
values = result;
}
}
This is then called in my onCreate method as new GetRoutes().execute("test");
.
However, when I try to run this, my app crashes as a result of a NullPointerException (logcat is available here).
Could you please guide me on how I can fix this?
For further reference, my RouteReader class is as follows:
public class RouteReader extends Reader{
public final static String routeURL =
"http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a=ttc";
private Map<String, String> routes;
public RouteReader()
throws IOException, ArrayIndexOutOfBoundsException{
super(new URL(routeURL));
routes = xmlToMap();
}
public String[] getRoutes(){
return (String[]) routes.keySet().toArray();
}
public String getRouteNum(String route){
return routes.get(route);
}
private Map<String, String> xmlToMap()
throws IOException, ArrayIndexOutOfBoundsException{
Map<String, String> data = new HashMap<String, String>();
String input;
do{
input = getReader().readLine();
if (input.startsWith("<route")){
String[] read = input.split("\"");
data.put(read[3], read[1]);
}
}while (!input.equals("</body>"));
return data;
}
}
We'll your log shows a NumberFormatException at RouteReader lines 35. That's not a NullPointerException - it's a failure to parse a string as an integer, because the string is "1S". You should work out what you want to do with invalid data, and handle it appropriately.
Additionally, you're comparing strings with == instead of equals, which is almost never what you want to do. Personally I wouldn't try to use string operations to parse the XML in the first place: use an XML parser... That's what it's there for. Your current approach is very brittle in the face of seemingly-harmless changes in the XML format.
See more on this question at Stackoverflow