How to solve SAXParseExecption in android? - android

I am developing an application,In my application,I am displaying lot of images from url using DOM xml parsing,It is working fine,but some time i got org.xml.sax.SAXParseException: Unexpected end of the documentin my xml parsing handler.How to solve this problem,please help me.This is my xml parsing handler code
public String parse_bannerlink() throws UnknownHostException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String bannerlink=null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
org.w3c.dom.Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("partypicbanner");
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("link")) {
bannerlink=property.getFirstChild().getNodeValue();
}
}}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return bannerlink;
}
Thanks all

Try to validate your input file with any xml-validator, for example this: Xml validator

You are definitely not parsing that document using DOM you are parsing it using SAX. I'd check the document you are trying to parse as apparently that document is not valid.
UPDATE: Apparently I was wrong. Didn't know that DOM throws that exception too.

Related

Parse multiple values and store [ANDROID]

I would like to parse a webservice response in xml on my android.
The way most "easy" what I did was this:
public String valor;
public static FormasDePagamento[] parseXML(String xml)
throws ParserConfigurationException, SAXException, IOException {
InputSource is = new InputSource(new StringReader(xml));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
FormasDePagamento[] formas = new FormasDePagamento[7];
for (int i = 0; i < 7; i++) {
formas[i] = new FormasDePagamento();
formas[i].valor = doc.getElementsByTagName("VALOR").item(i)
.getTextContent();
}
But now what I need is to get all that are in the result (which can be 7, but can also be 500 results) and in addition, each store a list to be displayed as a list in activity.
How can I develop this? Thank U!
You can pass your obtained list to an ArrayAdapter and show it on a ListView
ArrayAdapter<FormaDePagamento> adapter = new ArrayAdapter<FormaDePagamento>(context,android.R.layout_simple_list_item_1,parseXML(xml));
yourListView.setAdapter(adapter);
ArrayAdapter gets the toString() of your class, so remember to override it to show whatever info you want

XML parsing working fine with Android 2.2, 2.3 but not with ICS

I am fetching the some data from the server using XML parsing that is not working with ICS version of Android.here is my please tell me what correction do I make so that I should also run on ICS...(It's working fine with lower versions). Here is my code
try {
URL url = new URL(
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("file");
namephoto = new String[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("file");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
namephoto[i] = ((Node) nameList.item(0)).getNodeValue();
}
} catch (Exception e) {
Log.e("name", "" + e);
}
photobitmap = new Bitmap[namephoto.length];
setPhotoBackground(namephoto[index_photo]);
My XML code like this.
<?xml version="1.0"?>
-<root><file>1 a.JPG</file><file>2 b.JPG</file><file>3 c.JPG</file><file>4 d.JPG</file> </root>
i have got the solution myself.. Here is the code which is compatible with Android 4.0 as well as rest of the android versions...Just change the for loop like this.
for (int i = 0; i < nodeList.getLength(); i++) {
Node name = nodeList.item(i);
NodeList nodeEle = name.getChildNodes();
namephoto[i] = ((Node) nodeEle.item(0)).getNodeValue();
}

How to use DOM to read XML within Android applications correctly?

I'm able to get the information I want if the XML file is stored locally on my machine, but reading it when stored on the phone isn't working very well.
I've tried XMLPullParser but it extracts binary information about the id names etc and I'd like the actual name.
Code:
final String ANDROID_ID = "android:id";
try {
File fXmlFile = new File("res/layout/page1.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Button");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if (eElement.hasAttribute(ANDROID_ID))
System.out.println("ID: "
+ eElement.getAttribute(ANDROID_ID));
}
}
}
catch (Exception e) {
System.out.println("Catch");
e.printStackTrace();
}
in the XmlPullParser documentation there is a getAttributeCount() and getAttributeByName(int index) that might be useful. You must use it in START_TAG
Over XML parsing this link describes well. Here you can find other parsers too with xmlPullParser.

Parsing a XML HttpResponse

I'm trying to parse the XML HttpResponse i get from a HttpPost to a server (last.fm), for a last.fm android app. If i simply parse it to string i can see it being a normal xml string, with all the desired information. But i just cant parse the single NameValuePairs. This is my HttpResponse object:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
I tried two different things and non of them worked. First i tried to retrieve the NameValuePairs:
List<NameValuePair> answer = URLEncodedUtils.parse(r_entity);
String name = "empty";
String playcount = "empty";
for (int i = 0; i < answer.size(); i++){
if (answer.get(i).getName().equals("name")){
name = answer.get(i).getValue();
} else if (answer.get(i).getName().equals("playcount")){
playcount = answer.get(i).getValue();
}
}
After this code, name and playcount remain "empty". So i tried to use a XML Parser:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document answer = db.parse(new DataInputStream(r_entity.getContent()));
NodeList nl = answer.getElementsByTagName("playcount");
String playcount = "empty";
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
Node fc = n.getFirstChild();
playcount Url = fc.getNodeValue();
}
This seems to fail much earlier since it doesn't even get to setting the playcount variable. But like i said if i perform this:
EntityUtils.toString(r_entity);
I will get a perfect xml string. So it should no problem to pars it since the HttpResponse contains the correct information. What am i doing wrong?
I solved it. The DOM XML parser needed a little more adjustment:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(inStream);
String playcount = "empty";
NodeList nl = doc.getElementsByTagName("playcount");
for(int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
playcount = nameElement.getFirstChild().getNodeValue().trim();
}
}
This is a very good tutorial on parsing XML from a feed.
You can use it to build more robust apps that need to parse XML feeds
I hope it helps
if (answer.get(i).getName() == "name"){
You can't use == to compare a String
When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.
Here's the correct way to compare two strings.
String abc = "abc"; String def = "def";
// Bad way
if ( (abc + def) == "abcdef" )
{
......
}
// Good way
if ( (abc + def).equals("abcdef") )
{
.....
}
Taken from Top Ten Errors Java Programmers Make

parser 2.1 and 2.2

i using the follwing Code to retrive XML element text using getElementsByTagName
this code success in 2.2 and Failed in 2.1
any idea ?
URL metafeedUrl = new URL("http://x..../Y.xml")
URLConnection connection ;
connection= metafeedUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection ;
int resposnseCode= httpConnection.getResponseCode() ;
if (resposnseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf ;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the Earthquakes entry
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
//ArrayList<Album> Albums = new ArrayList<Album>();
/* Returns a NodeList of all descendant Elements with a given tag name, in document order.*/
NodeList nl = docEle.getElementsByTagName("entry");
if (nl!=null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Element entry = (Element)nl.item(i);
/* Now on every property in Entry **/
Element title =(Element)entry.getElementsByTagName("title").item(0);
*Here i Get an Error*
String album_Title = title.getTextContent();
Element id =(Element)entry.getElementsByTagName("id").item(0);
String album_id = id.getTextContent(); //
getTextContent() is not supported in API 7 (Android 2.1). It was introduced in API 8 (2.2).
Assuming a predictable result from the server, you can use the following code:
Node n = aNodeList.item(i);
String strValue = n.getFirstChild().getNodeValue();
// as opposed to the String strValue = n.getTextContent();
If the element may be empty, then you'd want to check the child count first.

Categories

Resources