Parsing Xml From Web
I'm developing an Android app, I would read an XML file from web but it doesn't work. I'm new on Android and I don't know why it doesn't work. This is my code, could someone help m
Solution 1:
First of all, you can not access internet locations without an AsyncTask
. You can not do that on the main thread
. Google it.
Secondly, xpp.next()
should have been placed inside the loop.
Thirdly, @Kamuy's solution works too but in the same scenario as below.
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newWebService() {
@OverrideprotectedObjectdoInBackground(Object... params) {
try {
List<String> arr = newArrayList<String>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
URL input = newURL("http://whatdowedo.altervista.org/griffith_list.xml");
xpp.setInput(input.openStream(), null);
//
int eventType = xpp.getEventType();
String currentTag = null;
//String title = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
} elseif (eventType == XmlPullParser.TEXT) {
if ("title".equals(currentTag)) {
title = xpp.getText().trim();
if(title.length()>0) {
arr.add(title);
System.out.println(title);
}
}
}
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
returnnull;
}
}.execute();
}
abstractclassWebServiceextendsAsyncTask<Object, Void, Object> {
publicWebService() {
super();
}
@OverrideprotectedvoidonPreExecute() {
}
@OverrideprotectedabstractObjectdoInBackground(Object... params);
@OverrideprotectedvoidonPostExecute(Object result) {
}
}
Replace the String
array with your FilmList
and that should be all.
Just say thanks.
Solution 2:
Example:
try {
URL url= newURL(/*your xml url*/);
URLConnectionconn= url.openConnection();
DocumentBuilderFactoryfactory= DocumentBuilderFactory.newInstance();
DocumentBuilderbuilder= factory.newDocumentBuilder();
Documentdoc= builder.parse(conn.getInputStream());
NodeListnodes= doc.getElementsByTagName(/*tag from xml file*/);
for (inti=0; i < nodes.getLength(); i++) {
Elementelement= (Element) nodes.item(i);
NodeListtitle= element.getElementsByTagName(/*item within the tag*/);
Elementline= (Element) title.item(0);
phoneNumberList.add(line.getTextContent());
}
}
catch (Exception e) {
e.printStackTrace();
}
In my example, my XML file looks a little like:
<numbers><phone><stringname = "phonenumber1">555-555-5555</string></phone><phone><stringname = "phonenumber2">555-555-5555</string></phone>
and I would replace /tag from xml file/ with "phone" and /item within the tag/ with "string".
Post a Comment for "Parsing Xml From Web"