rss reader method not support uses-sdk - android

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?

Related

Android - RSS reader: URL forced to mobile address

On the image you can see my origiginal URL for the RSS (http://www.fyens.dk/rss/sport) is changed to go to the mobile site (http://mobil.fyens.dk/modules/mobile). How can I avoid this? I can't read the RSS feed from the mobile site.
try {
URL url = new URL("http://www.fyens.dk/rss/sport");
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++) {
The program jumps to a
catch (Exception e) {
e.printStackTrace();
}
when it reaches the line
Document document = db.parse(is);
The site is most likely doing a redirection based on User Agent. You want to fool the site with a different user agent string.
Try doing:
conn.setRequestProperty("User-Agent", "The user agent you want to use");
You will want to use a user agent string that corresponds to a desktop browser. Check this list: http://www.useragentstring.com/pages/Chrome/

DOMParser for android

Im leaning how to use DOm parser for android well I use the Servivce of example androidHive.com
"http://api.androidhive.info/pizza/?format=xml"
Im using URLCOnnection to connect to a server which it has a username and password to connect but it returns nullPointerException.
protected static InputStream getInputStream(URL url) {
try{
URLConnection UrlConn = url.openConnection();
UrlConn.setDoInput (true);
UrlConn.setRequestProperty ("trust",
URLEncoder.encode(User,Pass);
UrlConn .connect ();
return UrlConn.getInputStream();
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
here is my code:
public static void domparser() throws Exception {
//Get the DOM Builder Factory
pizza=new ArrayList<HashMap<String,String>>();
String urlN="http://api.androidhive.info/pizza/?format=xml";
URL url=new URL(urlN);
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
Document document =
builder.parse(getInputStream(url));
Element root = document.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("menu");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node=nodeList.item(i);
NodeList list=node.getChildNodes();
for(int x=0;list.getLength()>x;x++){
//map=new HashMap<String,String>();
HashMap<String,String> map=new HashMap<String,String>();
Node element=list.item(x);
String name=element.getNodeName();
if (name.equalsIgnoreCase("id")){
map.put("Id",element.getFirstChild().getNodeValue().toString());
} else if (name.equalsIgnoreCase("name")){
map.put("name",element.getFirstChild().getNodeValue().toString());
}
pizza.add(map);
}
}
}
Could it be that your http client code throws an excetion during network access and returned the null value in one of your catch-blocks?
Reasons could be that no internet connection is available, permissions are missing in the AndroidManifest.xml, the wrong request method is used or problems with the timeout occurred.
Maybe debugging or logging the request code, the catch-blocks and the response entity could be useful for finding the core problem. In this article example code for checking the internet connection by using the ConnectivityManager system service and http connection is available.

How to reading XML from a URL in 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.

android DOM parsing with entities in tags

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;

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