Java 列表中填写了最后的数据,而不是插入顺序(Android)
我有一个如下所示的XML解析器:Java 列表中填写了最后的数据,而不是插入顺序(Android),java,android,list,mobile,xml-parsing,Java,Android,List,Mobile,Xml Parsing,我有一个如下所示的XML解析器: public class XMLParser { public static void XMLParser(){ } public List<itemRSS> parse(InputStream inputStream) throws XmlPullParserException, IOException { String title = null; String link = null; String
public class XMLParser {
public static void XMLParser(){
}
public List<itemRSS> parse(InputStream inputStream) throws XmlPullParserException,
IOException {
String title = null;
String link = null;
String description = null;
boolean isItem = false;
List<itemRSS> items = new ArrayList<>();
try {
XmlPullParser xmlPullParser = Xml.newPullParser();
xmlPullParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
xmlPullParser.setInput(inputStream, null);
xmlPullParser.nextTag();
while (xmlPullParser.next() != XmlPullParser.END_DOCUMENT) {
int eventType = xmlPullParser.getEventType();
String name = xmlPullParser.getName();
if(name == null)
continue;
if(eventType == XmlPullParser.END_TAG) {
if(name.equalsIgnoreCase("item")) {
isItem = false;
}
continue;
}
if (eventType == XmlPullParser.START_TAG) {
if(name.equalsIgnoreCase("item")) {
isItem = true;
continue;
}
}
Log.d("MyXmlParser", "Parsing name ==> " + name);
String result = "";
if (xmlPullParser.next() == XmlPullParser.TEXT) {
result = xmlPullParser.getText();
xmlPullParser.nextTag();
}
if (name.equalsIgnoreCase("title")) {
title = result;
} else if (name.equalsIgnoreCase("link")) {
link = result;
} else if (name.equalsIgnoreCase("description")) {
description = result;
}
if (title != null && link != null && description != null) {
if(isItem) {
itemRSS item = new itemRSS(title, description, link);
items.add(item);
}
else {
System.out.println("leo: " + title);
//mFeedTitle = title;
//mFeedLink = link;
// mFeedDescription = description;
}
title = null;
link = null;
description = null;
isItem = false;
}
}
return items;
} finally {
inputStream.close();
}
}
}
基本上,当执行完成时,它看起来就像是{4,4,4,4},而不是按照{1,2,3,4}的顺序添加到列表中
这怎么会发生?我的意图是做一个简单的RSS提要阅读器,所以这个解析器就是我如何从提要获取数据到一个数组,然后我将数组设置为recycledView的适配器。到目前为止效果还不错,但它只是写了一长串最后添加的标题,而不是正确的顺序
我跟踪了上面的错误代码,我很确定这就是问题所在,但我不知道如何解决这个问题
提前感谢。代码“看起来”是正确的,因为每次循环迭代都要创建一个新的项目对象(有时人们一直在添加相同的对象)
这里真正的答案是:您需要更多的跟踪(或者学习如何使用调试器)。只需确保每个重要信息对您来说都是可见的
根据您的更新,itemRSS类很可能正在使用静态字段?您知道当类的所有实例共享其字段时;这就解释了我们在这里看到的情况。旁注:java中的类名是大写的;因此,itemRSS对有经验的java程序员来说是相当误导的。我知道它在每次迭代中都会发生,就像这样:{1}->{2,2}->{3,3,3}->{4,4,4,4},但我仍然不知道为什么,并提示:增强的调试支持是以“每次更新1次投票”计费的哦,天哪,这是静态的东西。我一定是在编程时在代码的其他地方使用了自动更正功能,然后忘记了!!荒唐的我会核实你的答案的,谢谢!!
if (title != null && link != null && description != null) {
if(isItem) {
itemRSS item = new itemRSS(title, description, link);
items.add(item);
}