I am trying to fetch checkin locations from Google places API but I am getting error for XML FileNotFoundException when I try to read it through url.openStream(). My key is correct because I tried using it in some other URL in browser. If someone has used this feature then please let me know how to do this. Here is my code:
public String checkingMessage()
{
String strURL = "https://maps.googleapis.com/maps/api/place/check-in/xml?sensor=true&key=" + GOOGLE_API_KEY;
URL url;
try
{
url = new URL(strURL.replace(" ", "%20"));
// Standard of reading a XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(url.openStream()));
// Create a XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// Create a XPath object
XPath xpath = xFactory.newXPath();
// Compile the XPath expression
expr = xpath.compile("//reference/text()");
// Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
String answer = nodes.item(0).getNodeValue();
Toast.makeText(getApplicationContext(), answer, Toast.LENGTH_LONG);
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
If I use direct url in browser, I get following error:
400: Your client has issued a malformed or illegal request. That’s all we know.
I dont know json parsing, so I am using XML. Output I believe should be like this, hence I am trying to fetch value of reference:
<CheckInRequest>
<reference>place_reference</reference>
</CheckInRequest>
Update : I tried using HttpResponse and get response into Entity as follows
if (httpResponse.getStatusLine().getStatusCode() == 200){
strResult = EntityUtils.toString(httpResponse.getEntity());
}
But then I get MalFormedException on
doc = builder.parse(strResult); // doc is Document type
Either ways how can I get xml result into doc
I think you are trying to fetch check-in locations. I would like to do the same. But the check-in API seems to be POST-only at the moment, at least that's how I read the API documentation. Meaning your application can check-in, but you cannot query who checked in where (not even you yourself).
Related
I'm using google map route for my own android application. 2 days ago it worked well, but after that when the application runs its giving me errors via logcat. Can any body tell me a reason and solution for this problem.
org.xml.sax.SAXParseException: unterminated entity ref (position:ENTITY_REF :799 in java.io.InputStreamReader#406cdeb0)
private String[] getDirectionData(String sourceLat, String sourceLong, String destinationLat, String destinationLong) {
String urlString = "http://maps.google.com/maps?f=d&hl=en&" +"saddr="+sourceLat+","+sourceLong+"&daddr="+destinationLat+","+destinationLong + "&ie=UTF8&0&om=0&output=kml";
Log.d("URL", urlString);
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
String pathConent = "";
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
} catch (Exception e) {
Log.w("Error in google map",e);
}
NodeList nl = doc.getElementsByTagName("LineString");
for (int s = 0; s < nl.getLength(); s++) {
Node rootNode = nl.item(s);
NodeList configItems = rootNode.getChildNodes();
for (int x = 0; x < configItems.getLength(); x++) {
Node lineStringNode = configItems.item(x);
NodeList path = lineStringNode.getChildNodes();
pathConent = path.item(0).getNodeValue();
}
}
String[] tempContent = pathConent.split(" ");
return tempContent;
}
In my case this problem appeared on a .png file inside /res/drawable folder. It is a bug, and it was reported here. So, for future reference, if you are facing it on a drawable, check that out. To summarize, update your ADT to, at least, the version 21.0.1.
I have encountered the same problem. After debugging, I found that it was caused by the '&' character. it should be escaped
I dont know sure but I think is because output=kml is not longer available a lot of users are having troubles with it.
The error message is pretty suggestive: The ref tag is unterminated, e.g. the <ref> doesn't have an enclosing </ref> pair. Validate your XML input with a tool like this.
I was myself facing the same problem. This exception is coming because some important KML elements have been deprecated by google recently. For example, refer GeometryCollection .
If your code tries to find any such elements in the received document, it might throw
an SAXParseException: unterminated entity ref .
They have introduced a new API for Maps. It is available here .
I myself downloaded the kml file, and stored it in the device. When I had a look at it
using the editor, I did not find the element my code was looking for. However, if you use the kml file to find a route in the latest Chrome Version, it works.
I got the same problem. It was in a .png image file. The problem occurred after I edited the file. I searched for the solution but after that I cleaned my project using "clean.." option under "project" tab. SO finally I got rid of that "
I m new to Android (porting iOS/Objective C app ) and I have to read an XML (with some nodes in JSON) file returned by a WebService
the response looks like that:
<SOAP-ENV:Envelope><SOAP-ENV:Body><ns1:TPLoginResponse><TPLoginResult>[{"content": "some json content...."]</TPLoginResult></ns1:TPLoginResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
how can I simply get the content of TPLoginResult ?
I tried :
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
SoapObject SoapResponse = (SoapObject)envelope.bodyIn;
Log.e("Info", "response : " + SoapResponse.toString() ); // content is successfully received here
String SResponse = SoapResponse.toString();
Log.e("Info", "DocumentBuilderFactory" );
// parse the XML as a W3C Document
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse( new InputSource(new StringReader(SResponse)) );
NodeList nList = document.getElementsByTagName("TPLoginResult");
Log.e("info","nList length : " + nList.getLength());
but I need a 0 length nList ...
I also tryed :
NodeList nList = document.getElementsByTagName("ns1:TPLoginResponse");
but same 0 length result..
Any suggestions ?
I think the key is in this line:
builderFactory.setNamespaceAware(true);
if you comment that line you'd be able to get the element with
document.getElementsByTagName("TPLoginResponse");
otherwise, you'll probably need to use:
document.getElementsByTagNameNS(namespaceURI,tag);
but i have never used the last line, so i can't help you there.
please let me know how that works for you, i'm interested.
KSOAP Android is a very useful tool to consume SOAP web-services. I use this tool in all my Android applications. And I can say that it works well.
You can find examples in their wiki and all over internet.
Finally I found that it is more easy usign the ksoap methods
String LoginResponse = SoapResponse.getProperty(0).toString();
i am new in android development, i don't know how to parse data from xml, so please help.
this is my Xml which i have to parse.
<MediaFeedRoot>
<MediaTitle>hiiii</MediaTitle>
<MediaDescription>hellooooo.</MediaDescription>
<FeedPath>how r u</FeedPath>
</MediaFeedRoot>
Thanx in advance.
I dont understand that why people ask the question here without searching properly on net.Please do remember that search on net before asking anything here....
Below is the link where you can find a very good tutorial about xml parsing...
http://www.androidpeople.com/android-xml-parsing-tutorial-%E2%80%93-using-domparser
My suggestion is starting from the basic step:
think about your xml file connection: url? local?
instance a DocumentBuilderFactory and a builder
DocumentBuilder dBuilder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
OR
URLConnection conn = new URL(url).openConnection();
InputStream
inputXml = conn.getInputStream();
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document xmlDoc = docBuilder.parse(inputXml);
Parsing XML file:
Document xmlDom = dBuilder.parse(xmlFile);
After that, it turns a xml file into DOM or Tree structure, and you have to travel a node by node.
In your case, you need to get content. Here is an example:
String getContent(Document doc, String tagName){
String result = "";
NodeList nList = doc.getElementsByTagName(tagName);
if(nList.getLength()>0){
Element eElement = (Element)nList.item(0);
String ranking = eElement.getTextContent();
if(!"".equals(ranking)){
result = String.valueOf(ranking);
}
}
return result;
}
return of the getContent(xmlDom,"MediaTitle") is "hiiii".
Good luck!
Xml parsing api is throwing sax parse exception, If i try to parse a xml file which has attributes at root node.
One thing i have noticed is that, this happens if there is a UTF-8 BOM character at the start of the string, if i remove the BOM character things work fine. This code is working fine on 3.0 sdk and below, i saw this problem only in 3.1
am using following parser:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = null;
StringReader sr = new StringReader(xmlString);
InputSource is = new InputSource(sr);
doc = builder.parse(is);
Try this:
public Document parse(String xml) throws ParsingFailedException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//encode the xml to UTF -8
ByteArrayInputStream encXML = new ByteArrayInputStream(xml.getBytes("UTF8"));
Document doc = builder.parse(encXML);
log.error("XML parsing OK");
return doc;
} catch (Exception e) {
log.error("Parser Error:" + e.getMessage());
throw new ParsingFailedException("Failed to parse XML : Document not well formed", e);
}
}
Thanks evilone,
I have opened a issue with google, and they will be fixing this in their branch.
http://code.google.com/p/android/issues/detail?id=16892
Comments from google developer:
"I've prepared a fix for the root problem in our internal Honeycomb tree. But you don't need the fix for your code. Your parseXml method should just take an InputStream rather than a String. You can pass that directly to the InputSource constructor."
I might like to parse the following XML that contains entrities.
<node>
<text><title>foo fo <BR>bar bar </title></text>
</node>
The parsing works. But after the entrities I do not receive any output. Using CDATA is not possible at the position.
I'm using the following code:
urlConnection.getInputStream());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(in);
Does anyone got an idea?
Thx in advance!
CDATA usage is never necessary; so that's neither problem or a solution. But how do you actually tell there is no text? It is quite possible that you just have multiple adjacent text nodes -- underlying parsers often return multiple text segements (and esp. when there are entities). You can use a DOM method to "normalize" text content that an Element contains, to replace adjacent Text nodes with just a single one. But without this you should never assume all text is within the first (and only) Text node.
If there are no nodes, it is possible that the parser Android bundles is buggy. I think they include an old version of xpp or something, and it might have issues (compared to more polished parsers like Xerces or Woodstox). But I would first make sure it's not just case of "hidden" nodes.
http://code.google.com/p/android/issues/detail?id=2607
I found out, other have a similar problem. There Bug in Android 2.0.1 and 2.1. I solved this Problem by using the sax parser.
My name is Divy Dhiman i am a senior android developer
I had done the XML parsing by the same thing you can do it by entity or by node aur by fetching literal control that's depend on you.
private class MyAsyncTask extends AsyncTask
{
#Override
protected String doInBackground(String... abc) {
try {
URL url = new URL(jksbvlds);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("quote");
if(nl != null && nl.getLength()>0)
{
for(int i = 0; i<nl.getLength();i++ )
{
StockInfo theStock = getStockInformation(docEle);
name = theStock.getName();
yearLow = theStock.getYearLow();
yearHigh = theStock.getYearHigh();
daysLow = theStock.getDaysLow();
daysHigh = theStock.getDaysHigh();
lastTradePriceonly = theStock.getLastTradePriceonly();
change = theStock.getChange();
daysRange = theStock.getDaysRange();
}
}
}
}
catch(MalformedURLException e)
{
Log.d(TAG,"MalformedURLException",e);
}
catch(IOException e)
{
Log.d(TAG,"IOException",e);
}
catch (ParserConfigurationException e) {
Log.d(TAG,"ParserConfigurationException", e);
}
catch (SAXException e) {
Log.d(TAG,"SAXException",e);
}
finally{}
return null;