How to reading XML from a URL in Android - android

I want to read a XML document from a URL:
public void DownloadXmlFile() throws IOException{
//TODO
String url = "http://api.m1858.com/coursebook.xml";
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
}
I get an Error Exception
android.os.NetworkOnMainThreadException
I added uses-permission in manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

This is not an XML Problem its a Strict Mode Problem.
You should'nt do time intensiv things in Gui Thread, do it in a own Thread.
Blogpost with introduction
Developers API infos
BestPracties
However, you can disable it, but you shouldt ;)
see here

there are two step for read data from server...
1.Make a HTTP request to get the data from the webservice
2.Parse a XML document and read the contents
try
{
URL url = new URL("http://www.w3schools.com/xml/note.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("note");
/** Assign textview array lenght by arraylist size */
to = new TextView[nodeList.getLength()];
from = new TextView[nodeList.getLength()];
heading = new TextView[nodeList.getLength()];
body = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
to[i] = new TextView(this);
from[i] = new TextView(this);
body[i] = new TextView(this);
heading[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList toList = fstElmnt.getElementsByTagName("to");
Element nameElement = (Element) toList.item(0);
toList = nameElement.getChildNodes();
to[i].setText("To = "+ ((Node) toList.item(0)).getNodeValue());
NodeList fromList = fstElmnt.getElementsByTagName("from");
Element fromElement = (Element) fromList.item(0);
fromList = fromElement.getChildNodes();
from[i].setText("from = "+ ((Node) fromList.item(0)).getNodeValue());
NodeList headingList = fstElmnt.getElementsByTagName("heading");
Element headingElement = (Element) headingList.item(0);
headingList = headingElement.getChildNodes();
heading[i].setText("heading = "+ ((Node) headingList.item(0)).getNodeValue());
NodeList bodyList = fstElmnt.getElementsByTagName("body");
Element bodyElement = (Element) bodyList.item(0);
bodyList = bodyElement.getChildNodes();
body[i].setText("body = "+ ((Node) bodyList.item(0)).getNodeValue());
layout.addView(to[i]);
layout.addView(from[i]);
layout.addView(heading[i]);
layout.addView(body[i]);
}
}
catch (Exception e)
{
System.out.println("XML Pasing Excpetion = " + e);
}

Why you don't google or look for the error here on stackoverflow? It's full of answers...
You have to extend an AsyncTask to avoid the blocking of the GUI and do this kind of operation (as downloading or parsing stuff) in background.

Related

I'm trying to retrieve a value in span classes in an online XML-file in android.Help me with Sample Codes

I want to get value from the URL. please do some help or provide some helpful link where i can get the solution. Please help thanks in advance.
try {
URL url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("Cube");
Element element = (Element) nodes.item(0);
NodeList title = element.getElementsByTagName("Cube");
Element line = (Element) title.item(0);
Toast.makeText(this, "USD " + line.getTextContent().toString(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Checkout how to use:
XmlPullParser
in Android developer's website here

rss reader method not support uses-sdk

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?

Asnchronous task not working in Android 3.0 - 4.0 [duplicate]

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();
}

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();
}

XML URL parsing error

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("");

Categories

Resources