Reputation: 127
I'm new to Android development, and I'm using the New Boston tutorials to guide me through parsing some xml I have retrieved from an API, however it doesn't seem to be working for me I think the problem is somewhere in the handler, anywhere here is my code, I'll start with the relevent excerpt from the application class:
String test = null;
try {
//Assign XML to test string
test = new DownloadTextTask().execute(params).get();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
//create handler
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
//parse xml
xr.parse(test);
//Assign parsed xml to string
String information = "this is the access token: " + doingWork.getInformation();
//Output parsed XML
TextView myTextView = (TextView) findViewById(R.id.mytextview);
myTextView.setText(information);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now here is the handler:
XMLDataCollected info = new XMLDataCollected();
boolean isUser = false;
boolean isToken = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
if(localName.equals("user")){
isUser = true;
}else if(localName.equals("access_token")){
isToken = true;
}
}
public void characters (char ch[], int start, int length)
{
String str = null;
for (int i = start; i < start + length; i++) {
StringBuilder sb = new StringBuilder(str);
sb.append(ch[i]);
str = sb.toString();
}
if (isUser){
int u = Integer.parseInt(str);
info.setID(u);
}
else if(isToken){
info.setToken(str);
}
}
public String getInformation()
{
return info.dataToString();
}
XMLDataCollected Class:
public class XMLDataCollected {
int userId = 0;
String accessToken = null;
public void setID(int i){
userId = i;
}
public void setToken(String t){
accessToken = t;
}
public int getUserId(){
return userId;
}
public String dataToString(){
return accessToken;
}
And finally here is the XML that I am trying to parse:
<xml>
<user>1</user>
<access_token>a5923jh34gdhei592jdyeo3jk2354323ji4</access_token>
<status>Login Successful</status>
</xml>
Any help anyone can give me with this will be highly apreciated
Upvotes: 0
Views: 81
Reputation: 9794
I also followed that tutorial but I also didn't understand why it wasn't working. I did some research and came with XmlPullParser, it is very easy to use and works really well. Here is the documentation for the XmlPullParser:
http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
Hope it helps!
Upvotes: 1