Java AsyncTask返回错误
我一直在尝试使用Asynctask、以下内容和教程解析XML文件。我在我的活动中实现了一个类,如下所示:Java AsyncTask返回错误,java,android,android-asynctask,Java,Android,Android Asynctask,我一直在尝试使用Asynctask、以下内容和教程解析XML文件。我在我的活动中实现了一个类,如下所示: private class GetRoutes extends AsyncTask<String, Void, String[]> { @Override protected String[] doInBackground(String... urls) { String[] read; try{
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;
}
}
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;
}
}我们将看到,您的日志在RouterReader第35行显示数字格式异常。这不是NullPointerException-将字符串解析为整数是失败的,因为字符串是“1S”。您应该确定如何处理无效数据,并对其进行适当处理 此外,您将字符串与==进行比较,而不是与equals进行比较,这几乎不是您想要做的。就我个人而言,我不会首先尝试使用字符串操作来解析XML:使用XML解析器。。。这就是它的目的。面对XML格式中看似无害的更改,您当前的方法非常脆弱。从您的日志:
Caused by: java.lang.NumberFormatException: Invalid int: "1S"
这可能是由于以下原因造成的:
data.put(read[3], Integer.parseInt(read[1]));
啊,谢谢,我错过了“1”。我已经编辑了那门课,但我仍然得到了答案。这个错误让我想起了对AsyncTask类型的引用调用execute()时的情况,我的意思是删除了泛型类型。但如果您的调用是:new GetRoutes().execute(“test”);,那就好了。啊,谢谢,我错过了“1”。我已经编辑了那个类,但仍然得到一个错误。你能指导我吗?你建议我使用DOMparser吗?@mCode:可能,或者其他一些XML解析器。有很多选项可用。@mCode。引用docs“我们推荐XmlPullParser,这是在Android上解析XML的一种高效且可维护的方法。”@Raghundan:是的,尽管这是网络教程的一部分。目前还不清楚它是否始终是正确的解析器。对于在内存中保存整个DOM树不成问题的小文件,其他解析器可能会生成更简单的代码。