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.
Related
I use this method for get rss items
public static ArrayList<RssItem> getRssItems(String feedUrl) {
ArrayList<RssItem> rssItems = new ArrayList<RssItem>();
try {
URL url = new URL(feedUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(is);
Element element = document.getDocumentElement();
NodeList nodeList = element.getElementsByTagName("item");
if (nodeList.getLength() > 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
Element entry = (Element) nodeList.item(i);
Element _titleE = (Element) entry.getElementsByTagName(
"title").item(0);
Element _descriptionE = (Element) entry
.getElementsByTagName("description").item(0);
Element _pubDateE = (Element) entry
.getElementsByTagName("pubDate").item(0);
Element _linkE = (Element) entry.getElementsByTagName(
"link").item(0);
String _title = _titleE.getFirstChild().getNodeValue();
String _description = _descriptionE.getFirstChild()
.getNodeValue();
Date _pubDate = new Date(_pubDateE.getFirstChild()
.getNodeValue());
String _link = _linkE.getFirstChild().getNodeValue();
RssItem rssItem = new RssItem(_title, _description,
_pubDate, _link);
rssItems.add(rssItem);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return rssItems;
}
but when I set uses-sdk in manifest, after this string
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
execution proceeds to block catch. When I delete uses-sdk from manifest everything is OK. What I need to do to leave uses-sdk but it work?
The question doesn't really describe the problem very well, but making an educated guess, you are getting NetworkOnMainThreadException.
When you don't specify a targetSdkVersion in manifest, it defaults to 1 and all backwards-compatibility features are enabled, including allowing network operations on UI thread. When you specify a target SDK version >= 11 and actually run on API level 11 or higher, you'll get NetworkOnMainThreadException.
The fix is to do network operations on a background thread using e.g. AsyncTask.
Canonical reference: How to fix android.os.NetworkOnMainThreadException?
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.
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
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.
I'm trying to parse an xml file that I get by entering the url of that xml file as a parameter in my doInBackground function. Now I call this function 2 times.
During the first call it works fine.
During the second call it gives me a parsing error:
08-16 23:49:20.823 27735-28009/be.project.randomreader W/System.errīš org.xml.sax.SAXParseException: Unexpected token (position:TEXT {"success":{"tot...#1:210 in java.io.InputStreamReader#9e143cb)
Does it have to do something with the "?" sign and the "=" sign in my url?
How can I change my code to resolve this problem?
//first call:
ArrayList<String> url= new ArrayList<String>();
url.add("http://api.theysaidso.com/qod.xml");
url.add("");
new DownloadXML().execute(url);
//second call after a click event:
ArrayList<String> url= new ArrayList<String>();
url.add("http://api.theysaidso.com/");
url.add("qod?category=" + random);
new DownloadXML().execute(url);
private class DownloadXML extends AsyncTask<ArrayList<String>,Void,ArrayList> {
#Override
protected ArrayList doInBackground(ArrayList<String>... url) {
try {
ArrayList<String> urlLijst = url[0];
String query = URLEncoder.encode(urlLijst.get(1), "utf-8");
String url1 = urlLijst.get(0) + query;
URL url2 = new URL(url1); //.toString()
URLConnection conn = url2.openConnection();
DocumentBuilderFactory factory = documentBuilderFactor.get();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(conn.getInputStream());
parser.reset();
NodeList nodes = doc.getElementsByTagName("quotes");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("quote");
Element quote = (Element) title.item(0);
lijstQuotes.add(quote.getTextContent());
}
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("author");
Element author = (Element) title.item(0);
lijstQuotes.add(author.getTextContent());
}
}
}
}
Change your second call from
url.add("http://api.theysaidso.com/");
url.add("qod?category=" + random);
to
url.add("http://api.theysaidso.com/qod.xml?category=" + random);
theysaidso API seems to change its encoding based on the headers sent or explicit format request. By appending .xml you are forcing the format to be xml. In the other case you are getting back a json response and the parser fails. More info here
https://theysaidso.com/api
In the first call your
url[0] = "http://api.theysaidso.com/qod.xml"
In the second just:
"http://api.theysaidso.com/"
So, you didn't get the XML second time.
Try to change
url.add("http://api.theysaidso.com/");
url.add("qod?category=" + random);
into
url.add("http://api.theysaidso.com/qod?category=" + random);
url.add("");