My code gets a RSS feed and parses it. Code works fine, but is very slow in some functions (see time in code). Any suggestions?
URLConnection connection = feedUrl_.openConnection();
InputStream inputStream = connection.getInputStream(); // 15 sec
Reader reader = new InputStreamReader(inputStream, "UTF-8");
InputSource inputSource = new InputSource(reader);
doc = builder.parse(inputSource); // 60 sec
Buddy , try using XMLPullParser to parse data , it won't take much time to parse data hardly 6-7 secondes. Here is the code . Try this out:
onCreate()
{
try
{
URL url = null;
url = new URL("http://feeds.abcnews.com/abcnews/worldnewsheadlines");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); // extract the
// headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); // extract the link of
// article
}
} else if (eventType == XmlPullParser.END_TAG
&& xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
}
eventType = xpp.next(); // move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
I hope this will example will help you out. :)
The problem might be the emulator itself, since it has performance issues. I suggest that you test it on an actual device to determine whether the problem comes from the emulator or from the code.
If testing on a device is not possible for you at the moment, answers to this SO question suggest many tips to improve the emulator : Why is the Android emulator so slow? How can we speed up the Android emulator?
您可以使用Genymotion ,它非常快速,您可以通过adb访问日志。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.