Android - RSS reader: URL forced to mobile address - android

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/

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

Connect to a ipaddress programmatically to get the return value

I need to call a ip address say http://12.12.1.43:8080/xyzzz , this will return me a XML. But i am not sure how can i call this from android programmatically.
The server i am trying to access is remotely.
you need to parse the XML response received from the server like this
String uri = "http://12.12.1.43:8080/xyzzz ";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream xml = connection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml);

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.

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?

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;

Categories

Resources