Parse multiple values and store [ANDROID] - 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

Related

Parsing XML file stored in internal storage using DOM parser in android.

I have created an xml file in the device's internal storage as described on the android developers website. I now want to parse the file using DOM parser. What do i need to do to make the DOM parser read my XML file??
Here's a snippet:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(new InputSource(new StringReader(data)));
dom.getDocumentElement().normalize();
What do i need to put in the place of "data" in:
Document dom = db.parse(new InputSource(new StringReader(data)));
I know it's silly but any help would be appreciated.
You can make a input stream of the xml string like below and then getting nodes you can parse to get values.
InputStream is = new ByteArrayInputStream(theXMLString.getBytes("UTF-8"));
// Build XML document
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
Remember you are passing xml file as a string.
You can give FileInputStream in inputsource
Document dom = db.parse(new InputSource(new FileInputStream(data)));
For reading XML file, you should try below
FileInputStream in = new FileInputStream("/sdcard/text.txt");
StringBuffer data = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
in.close();
String finalData =data.toString(); // Here is your data.
Hope above may useful to you.
Try this code for parsing from Asset folder using DOM Parser :
DocumentBuilderFactory DBF;
DocumentBuilder DB;
Document dom;
Element elt;
DBF = DocumentBuilderFactory.newInstance();
DB = DBF.newDocumentBuilder();
dom = DB.parse(new InputSource(getAssets().open("city.xml")));
elt = dom.getDocumentElement();
NodeList items = elt.getElementsByTagName("item");
where item is Node element, add try ctch block as per the requirements.

How to get sessionId from server if the login is authenticated in android?

I'm validating the form data as the response I'm getting total feed of that URL but i need only session Id from that how can i do this.can any body help regarding this..
Now as below shown way i'm getting response from server how can i get required one from that..
<data>
<limit>
<uname>android</uname>
<pwd>androiddeveloper</pwd>
<sessionid>abcdef56789ghijkl90a<sessionid/>
</limit>
</data>
I solved it from this link and is worked fine for me thanks to that guy who solved it.
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();
}
}
You can fire query for that. If the user is authenticated then get user's userId and store in some static variable.
This might you need i think.

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.

How to solve SAXParseExecption in 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.

Categories

Resources