You are on page 1of 44

Android

Internet Content
Part 1 RSS Feeds

18
Victor Matos
Cleveland State University

Notes are based on:
Android Developers
http://developer.android.com/index.html
2 2 2
18. Android Internet Feeders

Internet
2
Communicating Via Internet















The image illustrates Year 2007 Internet Density. Colored dots represent number of IP addresses per dot-area.

Source: www.ipligence.com/worldmap/internet-map.jpg

3 3 3
18. Android Internet Feeders

Internet


3
USA & Worldwide Growth of Cellular Telephony

Figure taken from I am OK - A Conceptual Model for a Global Emergency System and Its Societal Impact (2007). Victor Matos and Ben Blake.
International Journal of Technology Knowledge and Society. Vol. 2 No. 5 pp.7-18 January 2007.



4 4 4
18. Android Internet Feeders

State of the Internet
4
References: http://royal.pingdom.com/2011/01/12/internet-2010-in-numbers/
http://mashable.com/2011/01/25/internet-size-infographic/



5 5 5
18. Android Internet Feeders

State of the Internet
5
References: http://royal.pingdom.com/2011/01/12/internet-2010-in-numbers/
http://mashable.com/2011/01/25/internet-size-infographic/



6 6 6
18. Android Internet Feeders

State of the Internet
6
References: http://royal.pingdom.com/2011/01/12/internet-2010-in-numbers/
http://mashable.com/2011/01/25/internet-size-infographic/



7 7 7
18. Android Internet Feeders

State of the Internet
7
References: http://royal.pingdom.com/2011/01/12/internet-2010-in-numbers/
http://mashable.com/2011/01/25/internet-size-infographic/



8
18. Android Internet Feeders

Internet
8
Background: RSS Feeds
RSS (most commonly translated as Really Simple Syndication but sometimes
Rich Site Summary) is a family of web feed formats used to publish frequently
updated workssuch as blog entries, news headlines, weather reports, audio
and videoin a standardized format.


An RSS document (which is called a web feed or channel) includes full or
summarized text (plus metadata), publishing dates and authorship.

Notes
Content distributors expose web feeds allowing users to subscribe to them.

Making a collection of web feeds accessible in one spot is known as
aggregation which is performed by an Internet aggregator.

9 9
18. Android Internet Feeders

Internet
9
Background: Web Feeds
Web feeds allow (client) software programs to check for summary updates
published on a website.

First version of RSS was created by Netscape around 1999.

A typical news feed (or channel) contains entries which may be:
headlines,
full-text articles excerpts,
summaries,
Thumbnails, and/or
links to content on a website along with various metadata

The Atom Syndication Format and RSS2.0 are common XML standards used
to organize, create and update web feeds (these formats have been
adopted by Google, Yahoo!, Apple/iTunes, CNN, NY Times,).



10 10
18. Android Internet Feeders

Internet
10
Background: Web Feeds
Common child elements of <channel> and <item>


Elements Description Type # allowed
LastMod Last modified date for this web page ISO 8601:1988 Date 0 or 1
Title Title String 0 or 1
Abstract Short description summarizing the article (200 characters
or less recommended)
String 0 or 1
Author Author String Any
Publisher Publisher String Any
Copyright Copyright String 0 or 1
PublicationDate Publication Date String 0 or 1
Logo Visual Logo for channel Logo element Any
Keywords Comma delimited keywords that match this channel String Any
Category A category to which this web page belongs in. The string
value is a URI to a CategoryDef element.
Category element Any
Ratings Rating of the channel by one or more ratings services.
(String found in PICS label meta tag.)
String Any
Schedule Schedule for keeping channel up to date Schedule element 0 or 1
UserSchedule Reference to a client/user specified schedule UserSchedule element 0 or 1
Reference: http://www.w3.org/TR/NOTE-CDFsubmit.html
11 11
18. Android Internet Feeders

Internet
11
Background: Web Feeds
Elements of <item>
A channel may contain any number of <item>s. An item may represent a
"story" -- much like a story in a newspaper or magazine.


Reference: http://www.w3.org/TR/NOTE-CDFsubmit.html
Element Description
title The title of the item.
link The URL of the item.
description The item synopsis.
author Email address of the author of the item.
category Includes the item in one or more categories.
comments URL of a page for comments relating to the item.
enclosure Describes a media object that is attached to the item.
guid A string that uniquely identifies the item.
pubDate Indicates when the item was published.
source The RSS channel that the item came from.
12 12
18. Android Internet Feeders

Internet
12
Background: Web Feeds
Example:


<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>RSS Title</title>
<description>This is an example of an RSS feed</description>
<link>http://www.someexamplerssdomain.com/main.html</link>
<lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000 </lastBuildDate>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>

<item>
<title>Example entry</title>
<description>Here is some text containing an interesting
description of the thing to be described. </description>
<link>http://www.wikipedia.org/</link>
<guid>unique string per item</guid>
<pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
</item>

</channel>
</rss>
Source: http://en.wikipedia.org/wiki/RSS
13
18. Android Internet Feeders

Internet Feeders
13
US weather:
http://www.weather.gov/view/national.php?map=on
The Weather Channel
http://rss.weather.com/weather/rss/local/44114?cm_ven=LWO&
cm_cat=rss&par=LWO_rss
World weather
http://www.rssweather.com/dir

News
http://www.npr.org/rss/
http://www.cnn.com/services/rss/
http://news.bbc.co.uk/2/hi/help/3223484.stm
http://www.nytimes.com/services/xml/rss/nyt/GlobalHome.xml

Money Exchange
http://themoneyconverter.com/RSSFeeds.aspx

Entertainment
http://www.nbclosangeles.com/rss/
http://www.movies.com/rss/

RSS Aggregator
http://www.rss-network.com/
http://www.nytimes.com/services/xml/rss/index.html


Corporate
http://www.toyota.co.jp/en/rss/rss-responsibility.html
http://home3.americanexpress.com/corp/rss/
http://www.aa.com/i18n/urls/rss.jsp



Internet
Consumer
Application
RSS Sources
14 14
18. Android Internet Feeders


14
How do RSS
feeds look like
when
using a
browser?
NPR National Public Radio
(17-Oct-2009)
http://www.npr.org/rss/






15
18. Android Internet Feeders

Internet Feeders
15
XML Version of the NPR RSS Feed (1/3 just a fragment!)




<?xml ver si on="1.0"?>
<?xml - st yl esheet t i t l e="XSL_formatting" type="text/xsl" href="/include/xsl/rss.xsl"?>

<rss xml ns: npr ="http://www.npr.org/rss/" xmlns:nprml="http://api.npr.org/nprml"
xml ns: i t unes="http://www.itunes.com/dtds/podcast-1.0.dtd"
xml ns: cont ent ="http://purl.org/rss/1.0/modules/content/" version="2.0">

<channel>

<t i t l e>NPR Topi cs: Sci ence</ t i t l e>

<l i nk>ht t p: / / www. npr . or g/ t empl at es/ st or y/ st or y. php?st or yI d=1007&amp; f t =1&amp; f =1007</ l i nk>

<descr i pt i on>The l at est heal t h and sci ence news. Updat es on medi ci ne, heal t hy
l i vi ng, nut r i t i on, dr ugs, di et , and advances i n sci ence and t echnol ogy.
Subscr i be t o t he Heal t h &amp; Sci ence podcast . </ descr i pt i on>

<copyr i ght >Copyr i ght 2009 NPR - For Per sonal Use Onl y</ copyr i ght >
<gener at or >NPR API RSS Gener at or 0. 93</ gener at or >
<l ast Bui l dDat e>Sat , 17 Oct 2009 14: 38: 00 - 0400</ l ast Bui l dDat e>

<i mage>
<ur l >ht t p: / / medi a. npr . or g/ i mages/ npr _news_123x20. gi f </ ur l >
<t i t l e>Sci ence</ t i t l e>
<l i nk>ht t p: / / www. npr . or g/ t empl at es/ st or y/ st or y. php?st or yI d=1007&amp; f t =1&amp; f =1007</ l i nk>
</ i mage>
16
18. Android Internet Feeders

Internet Feeders
16
XML Version of the NPR RSS Feed ( 2/3 just a fragment!)





<item>

<t i t l e>Cal i f or ni a Devel ops Ear t hquake Ear l y- War ni ng Syst em</ t i t l e>

<descr i pt i on>Li ves may be saved wi t h an ear t hquake ear l y- war ni ng syst em
&amp; mdash; t he ki nd t hat ' s al r eady i n pl ace i n J apan and Mexi co. But
her e i n t he U. S. , such a syst emi s st i l l sever al year s away. </ descr i pt i on>

<pubDat e>Sat , 17 Oct 2009 14: 38: 00 - 0400</ pubDat e>

<l i nk>ht t p: / / www. npr . or g/ t empl at es/ st or y/ st or y. php?st or yI d=113877510&amp; f t =1&amp; f =1007</ l i nk>

<gui d>ht t p: / / www. npr . or g/ t empl at es/ st or y/ st or y. php?st or yI d=113877510&amp; f t =1&amp; f =1007</ gui d>

<cont ent : encoded><! [ CDATA[ <p>Li ves may be saved wi t h an ear t hquake ear l y- war ni ng
syst em&mdash; t he ki nd t hat ' s al r eady i n pl ace i n J apan and Mexi co. But her e i n
t he U. S. , such a syst emi s st i l l sever al year s away. </ p><p><a
hr ef =" ht t p: / / www. npr . or g/ t empl at es/ emai l / emai l AFr i end. php?st or yI d=113877510" >&r aquo;
E- Mai l Thi s</ a>&nbsp; &nbsp; &nbsp; &nbsp; <a hr ef =" ht t p: / / del . i ci o. us/ post ?ur l =
ht t p%3A%2F%2Fwww. npr . or g%2Ft empl at es%2Fst or y%2Fst or y. php%3Fst or yI d%3D113877510" >&r aquo;
Add t o Del . i ci o. us</ a></ p>] ] ></ cont ent : encoded>

</ item>



Many <ITEM>s were intentionally removed to fit page size
17
18. Android Internet Feeders

Internet Feeders
17
XML Version of the NPR RSS Feed ( 3/3 just a fragment!)




<i t em>
<t i t l e>Mappi ng The Boundar i es Of The Sol ar Syst em</ t i t l e>
<descr i pt i on>NASA l aunched t he I nt er st el l ar Boundar y Expl or er ( I BEX)
spacecr af t l ast year t o i nvest i gat e t he edges of t he
hel i ospher e &amp; mdash; t he i nsul at i ng bubbl e t he sun cr eat es ar ound t he
sol ar syst em. I BEX pr i nci pal i nvest i gat or Davi d McComas r epor t s on t he
f i r st sur pr i si ng r esul t s. </ descr i pt i on>
<pubDat e>Fr i , 16 Oct 2009 13: 19: 00 - 0400</ pubDat e>
<l i nk>ht t p: / / www. npr . or g/ t empl at es/ st or y/ st or y. php?st or yI d=113870291&amp; f t =1&amp; f =1007</ l i nk>

<gui d>ht t p: / / www. npr . or g/ t empl at es/ st or y/ st or y. php?st or yI d=113870291&amp; f t =1&amp; f =1007</ gui d>
<cont ent : encoded><! [ CDATA[ <p>NASA l aunched t he I nt er st el l ar Boundar y Expl or er
( I BEX) spacecr af t l ast year t o i nvest i gat e t he edges of t he hel i ospher e
&mdash; t he i nsul at i ng bubbl e t he sun cr eat es ar ound t he sol ar syst em.
I BEX pr i nci pal i nvest i gat or Davi d McComas r epor t s on t he f i r st sur pr i si ng
r esul t s. </ p>
<p><a hr ef =" ht t p: / / www. npr . or g/ t empl at es/ emai l / emai l AFr i end. php?st or yI d=113870291" >&r aquo;
E- Mai l Thi s</ a>&nbsp; &nbsp; &nbsp; &nbsp; <a hr ef =" ht t p: / / del . i ci o. us/ post ?
ur l =ht t p%3A%2F%2Fwww. npr . or g%2Ft empl at es%2Fst or y%2Fst or y. php
%3Fst or yI d%3D113870291" >&r aquo;
Add t o Del . i ci o. us</ a></ p>] ] ></ cont ent : encoded>
</ i t em>

</ channel >
</ r ss>
<! - - Bur ned on demand at 2009- 10- 17 10: 49: 43- - >
<! - - LI VE - - >
<! - - Bur ned 10/ 17/ 2009 10: 49: 43. 407- - >
Many <ITEM>s were intentionally removed to fit page size
18
18. Android Internet Feeders

Internet Feeders
18
Representing the RSS XML as a Tree




. . . . . .
The Android API includes a
DocumentBuilderFactory
class to create this type of
tree from an input stream
19
18. Android Internet Feeders

Internet
19
Document Objcet Model (DOM).

The Document Object Model (DOM) is an application programming interface
API for valid HTML and well-formed XML documents.

With the Document Object Model, programmers can build documents, navigate
their structure, and add, modify, or delete elements and content.

Android includes support for DOM managers.





DocumentBuilder db = DocumentBuilderFactory
.newInstance();
.newDocumentBuilder();

Document dom = db.parse(someHttpInputStream);

20 20
18. Android Internet Feeders

Internet
20
Android includes the Apache HttpComponents API.
The HttpClient component (included in the API) facilitates building HTTP-aware
client applications (such as web browsers and web services) using very small
footprint .



HTTP Methods include:

GET
Requests a representation of the specified resource.
POST
Submits data to be processed to the identified resource.
HEAD
Same as GET but no message body.
PUT
Uploads a representation of the specified resource.
DELETE
Deletes the specified resource.
TRACE
Echoes back the received request.
OPTIONS
Returns the HTTP methods that the server supports for specified URL.
CONNECT
Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication
(HTTPS) through an unencrypted HTTP proxy.

Status Codes:
Ok, Bad Request, Not Found,
21
18. Android Internet Feeders

Internet
21
Putting all things together An Example Application

In this project we will develop an application to expose the material
typically broadcasted by National Public Radio (NPR) in Android
phones.






Internet
22
18. Android Internet Feeders

Internet
22
NPR Project Action Plan.

1. A little research indicates that NPR supports a number of web feeds among
them the following:




Topic URL
Top Stories
U.S. News
World News
Business
Health & Science
Arts & Entertainment
Politics & Society
People & Places
Opinion
http://www.npr.org/rss/rss.php?id=1001
http://www.npr.org/rss/rss.php?id=1003
http://www.npr.org/rss/rss.php?id=1004
http://www.npr.org/rss/rss.php?id=1006
http://www.npr.org/rss/rss.php?id=1007
http://www.npr.org/rss/rss.php?id=1008
http://www.npr.org/rss/rss.php?id=1012
http://www.npr.org/rss/rss.php?id=1021
http://www.npr.org/rss/rss.php?id=1057
23
18. Android Internet Feeders

Internet
23
NPR Project Action Plan.

2. We will display the main topics in a ListView widget from which the user will
make a selection. We use the associated web-feed to access the current
contents of the selected category.




Choose
Health & Science
24
18. Android Internet Feeders

Internet
24
NPR Project Action Plan.

3. The most current headlines of the selected
category are displayed. The User can scroll the list
and click on a particular subject.

Observe that individual lines correspond to the
XML <item> entries discussed earlier.

In the example we are interested in the
Health & Science subject. We want to know
about the efforts of mapping the Solar System.





25
18. Android Internet Feeders

Internet
25
NPR Project Action Plan.

4. A brief summary of the chosen topic is displayed
inside a DialogBox. The user is given the option of
closing the window or obtaining more information.








We want additional
information, so we click
the More button
26
18. Android Internet Feeders

Internet
26
NPR Project Action Plan.

5. The link held in the XML <item> currently displayed is given to a WebKit
based Activity. We use the Internet to access the page containing the detailed
subject.










We may opt for a non-
mobile page version
which may include a
number of additional
components such as
audio, pictures, video,
extensive text, etc.
27
18. Android Internet Feeders

Internet
27
Acquiring & Processing the NPR web-feed

1. Assume the RSS for Health & Science is
http://www.npr.org/rss/rss.php?id=1007.

2. The Java fragment in the next page uses the HttpComponents API.

3. The goal of this code is to grab the feed, and create a document holding the
tree parsed from the XML document.

4. The tree will be traversed looking for <item> elements similar to those
discussed earlier.

5. Each item will be dissected and the pieces arranged into a manageable
object form. Remember an <item> includes among other components
<title>, <description>, <link>, <datepublication>, etc.



28
18. Android Internet Feeders

Internet
28

/ / set t i ng & openi ng t he connect i on usi ng ur l Addr ess whi ch i s
/ / a val ue such as: ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1001

URL ur l = new URL( ur l Addr ess) ;
URLConnect i on connect i on = ur l . openConnect i on( ) ;

Ht t pURLConnect i on ht t pConnect i on =
( Ht t pURLConnect i on) connect i on;

i nt r esponseCode = ht t pConnect i on. get ResponseCode( ) ;

i f ( r esponseCode == Ht t pURLConnect i on. HTTP_OK) {
/ / get RSS- XML and make a document r epr esnt i ng
/ / t he par se t r ee const r uct ed f r omt he i nput
}


Main Programming Idea: Acquiring & Processing the NPR web-feed

/ / USE ht t pConnect i on t o get XML and make a document
/ / hol di ng t he par se t r ee const r uct ed f r omt he i nput
I nput St r eami n = ht t pConnect i on. get I nput St r eam( ) ;

/ / def i ne a document bui l der t o act on i ncomi ng st r eam
Document Bui l der db = Document Bui l der Fact or y. newInstance( )
. newDocument Bui l der ( ) ;
/ / make XML par se t r ee f or i ncomi ng RSS st r eam
Document dom= db. par se( i n) ;

/ / def i ne access nodes i n t he par se t r ee
El ement docEl e = dom. get Document El ement ( ) ;

/ / l ook f or i ndi vi dual news ( " i t ems" i n t hi s case)
/ / put i t ems i n a NodeLi st col l ect i on ( nl )
NodeLi st nl = docEl e. get El ement sByTagName( " i t em" ) ;

i f ( ( nl ! = nul l ) && ( nl . get Lengt h( ) > 0) ) {
f or ( i nt i = 0; i < nl . get Lengt h( ) ; i ++) {
di ssect Node( nl , i ) ;
}/ / f or
}/ / i f
29
18. Android Internet Feeders

Internet
29
Main Programming Idea: Acquiring & Processing the NPR web-feed

30
18. Android Internet Feeders

Internet
30
NPR Project Implementation

main.xml
(shows the main topics)










<?xml ver si on="1.0" encoding="utf-8"?>
<Li near Layout
andr oi d: i d="@+id/widget28"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="fill_parent"
andr oi d: or i ent at i on="vertical"
andr oi d: backgr ound="#ff000033"
xml ns: andr oi d="http://schemas.android.com/apk/res
/android"
>
<I mageVi ew
andr oi d: l ayout _wi dt h="70px"
andr oi d: l ayout _hei ght ="30px"
andr oi d: l ayout _x="2px"
andr oi d: l ayout _y="2px"
andr oi d: backgr ound="@drawable/logo_npr">
>
</ I mageVi ew>
<Li st Vi ew
andr oi d: i d="@+id/myListView"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
>
</ Li st Vi ew>
</ Li near Layout >

31
18. Android Internet Feeders

Internet
31
NPR Project Implementation

my_simple_list_item_1.xml
(shows individual rows of the
ListView widget)










<?xml ver si on="1.0" encoding="utf-8"?>

<Text Vi ew
xml ns: andr oi d="http://schemas.android.com/apk/res/andr
oid"
andr oi d: i d="@android:id/text1"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: gr avi t y="center_vertical"
andr oi d: paddi ngLef t ="10dip"
andr oi d: t ext Si ze="18sp"
andr oi d: mi nHei ght ="40sp"
/ >


32
18. Android Internet Feeders

Internet
32
Activity1: AndroNPR.java



/ / di spl ay a l i st of mai n subj ect s f or t he user t o choose a t opi c
package matos.internet;

import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class AndroNPR extends Activity {

Ar r ayAdapt er <St r i ng> aa;
Li st Vi ew myLi st Vi ew;
Cont ext cont ext ;
Si ngl eNewsI t emsel ect edNewsI t em;

33
18. Android Internet Feeders

Internet
33
Activity1: AndroNPR.java


St r i ng [ ] myUr l Addr ess = {
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1001" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1003" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1004" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1006" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1007" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1008" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1012" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1021" ,
" ht t p: / / www. npr . or g/ r ss/ r ss. php?i d=1057"
};
St r i ng [ ] myUr l Capt i on = {
" Top St or i es" ,
" U. S. News" ,
" Wor l d News" ,
" Busi ness" ,
" Heal t h & Sci ence" ,
" Ar t s & Ent er t ai nment " ,
" Pol i t i cs & Soci et y" ,
" Peopl e & Pl aces" ,
" Opi ni on"
};
St r i ng [ ] myUr l Addr ess2 = new String[myUrlAddressCaption.length];
St r i ng [ ] myUr l Capt i on2 = new String[myUrlAddressCaption.length];

34
18. Android Internet Feeders

Internet
34
Activity1: AndroNPR.java cont




@Over r i de
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
set Cont ent Vi ew( R. l ayout . main);
cont ext = get Appl i cat i onCont ext ( ) ;
this.setTitle("NPR Headline News v0.0 " + niceDate() );

myLi st Vi ew = ( Li st Vi ew) this.findViewById(R.id.myListView);
myLi st Vi ew. set OnI t emCl i ckLi st ener ( new OnItemClickListener() {
public void onItemClick(AdapterView<?> _av, View _v,
int _index, long _id) {
St r i ng ur l Addr ess = myUr l Addr ess[ _i ndex] ;
St r i ng ur l Capt i on = myUr l Capt i on[ _i ndex] ;
/ / cr eat e an I nt ent t o t al k t o Act i vi t y2
I nt ent Npr NewsDet ai l sI nt ent = new Intent(
Andr oNPR. this, NprNewsDetails.class);
/ / pr epar e a Bundl e and add t he dat a pi eces t o be sent
Bundl e myDat a = new Bundle();
myDat a. put St r i ng( " ur l Addr ess" , ur l Addr ess) ;
myDat a. put St r i ng( " ur l Capt i on" , ur l Capt i on) ;
Npr NewsDet ai l sI nt ent . put Ext r as( myDat a) ;
st ar t Act i vi t y( Npr NewsDet ai l sI nt ent ) ;
}
}) ;

35
18. Android Internet Feeders

Internet
35
Activity1: AndroNPR.java cont


/ / bi nd mai n cat egor y l i st ( Top News, . . . ) t o t he t he l i st Vi ew
/ / show l i st and get r eady f or user t o cl i ck on a cat egor y
int layoutID = R.layout.my_simple_list_item_1;
aa = new ArrayAdapter<String>(this, layoutID , myUrlCaption);
myLi st Vi ew. set Adapt er ( aa) ;
}/ / onCr eat e



public static String niceDate() {
Dat eFor mat Symbol s df s = new DateFormatSymbols();
/ / t o get shor t weekday- mont h_name St r i ng ar r ays
St r i ng shor t WeekdaysAr r ay[ ] = df s. get Shor t Weekdays( ) ;
St r i ng shor t Mont hAr r ay[ ] = df s. get Shor t Mont hs( ) ;
Cal endar cal = Cal endar . getInstance(Locale.US);
int dd = cal.get(Calendar.DAY_OF_MONTH);
int mm = cal.get(Calendar.MONTH);
St r i ng mmText = shor t Mont hAr r ay[ mm] ;
int yy = cal.get(Calendar.YEAR);
int wd = cal.get(Calendar.DAY_OF_WEEK);
St r i ng wdText = shor t WeekdaysAr r ay[ wd] ;
return ( wdText + " " + mmText + " " + dd + ", " + yy );
}/ / ni ceDat e

}/ / Andr oNPR
36
18. Android Internet Feeders

Internet
36
Activity2: NPRNewsDetails.java


package matos.internet;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
37
18. Android Internet Feeders

Internet
37
Activity2: NPRNewsDetails.java cont



public class NprNewsDetails extends Activity {
/ / a mai n cat egor y subj ect has al r eady been sel ect ed by t he user
/ / ( dat a <" ur l Capt i on" , " ur l Addr ess" > comes i n a bundl e sent
/ / by mai n, access web- f eed and show cor r espondi ng headl i nes
Ar r ayLi st <Si ngl eNewsI t em> newsLi st = new ArrayList<SingleNewsItem>();
Ar r ayAdapt er <St r i ng> aa;
Li st Vi ew myLi st Vi ew;
St r i ng ur l Addr ess = " " ;
St r i ng ur l Capt i on = " " ;
Si ngl eNewsI t emsel ect edNewsI t em;
Cont ext cont ext = get Appl i cat i on( ) ;

@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
set Cont ent Vi ew( R. l ayout . main);
myLi st Vi ew = ( Li st Vi ew) this.findViewById(R.id.myListView);

/ / cr eat e a l ocal I nt ent handl er ( needed t o pr ocess i nput par amet er s)
I nt ent myLocal I nt ent = get I nt ent ( ) ;

/ / gr ab t he dat a bundl e wi t h al l t he pi eces sent t o us
/ / i t cont ai ns 1. ur l - addr ess and 2. capt i on- t ext
Bundl e myBundl e = myLocal I nt ent . get Ext r as( ) ;
ur l Addr ess = myBundl e. get St r i ng( " ur l Addr ess" ) ;
ur l Capt i on = myBundl e. get St r i ng( " ur l Capt i on" ) ;
38
18. Android Internet Feeders

Internet
38
Activity2: NPRNewsDetails.java cont


/ / t op capt i on f or t hi s scr een
St r i ng t odaySt r = Andr oNPR. niceDate();
this.setTitle("NPR - " + urlCaption + " \t" + todayStr);

/ / cl i cki ng a l i ne shows mor e about sel ect ed news i t em
myLi st Vi ew = ( Li st Vi ew) this.findViewById(R.id.myListView);
myLi st Vi ew. set OnI t emCl i ckLi st ener ( new OnItemClickListener() {
public void onItemClick(AdapterView<?> _av, View _v,
int _index, long _id) {
sel ect edNewsI t em= newsLi st . get ( _i ndex) ;
showNi ceDi al ogBox( sel ect edNewsI t em, cont ext ) ;
}
}) ;
}/ / onCr eat e

@Over r i de
protected void onResume() {
super.onResume();
try {

URL ur l = new URL(urlAddress);
URLConnect i on connect i on;
connect i on = ur l . openConnect i on( ) ;

Ht t pURLConnect i on ht t pConnect i on = ( Ht t pURLConnect i on) connect i on;
int responseCode = httpConnection.getResponseCode();

39
18. Android Internet Feeders

Internet
39
Activity2: NPRNewsDetails.java cont


if (responseCode == HttpURLConnection.HTTP_OK) {
I nput St r eami n = ht t pConnect i on. get I nput St r eam( ) ;
Document Bui l der Fact or y dbf = Document Bui l der Fact or y. newInstance();
Document Bui l der db = dbf . newDocument Bui l der ( ) ;
Document dom= db. par se( i n) ;
El ement docEl e = dom. get Document El ement ( ) ;
/ / NodeLi st nl = docEl e. get El ement sByTagName( "ent r y" ) ;
NodeLi st nl = docEl e. get El ement sByTagName( "i t em") ;
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
di ssect Node( nl , i ) ;
}/ / f or
}/ / i f
}/ / i f
int layoutID = R.layout.my_simple_list_item_1;
Ar r ayAdapt er <Si ngl eNewsI t em> aaNews =
new ArrayAdapter<SingleNewsItem>(this, layoutID, newsList);
myLi st Vi ew. set Adapt er ( aaNews) ;
} catch (MalformedURLException e) {
e. pr i nt St ackTr ace( ) ;
} catch (IOException e) {
e. pr i nt St ackTr ace( ) ;
Toast . makeText(context, "Trouble!!!", 1).show();
} catch (ParserConfigurationException e) {
e. pr i nt St ackTr ace( ) ;
} catch (SAXException e) {
e. pr i nt St ackTr ace( ) ;
}
}/ / onResume
40
18. Android Internet Feeders

Internet
40
Activity2: NPRNewsDetails.java cont


public void dissectNode(NodeList nl, int i){
try {
El ement ent r y = ( El ement ) nl . i t em( i ) ;
El ement t i t l e = ( El ement ) ent r y. get El ement sByTagName(
" t i t l e" ) . i t em( 0) ;
El ement descr i pt i on = ( El ement ) ent r y. get El ement sByTagName(
" descr i pt i on" ) . i t em( 0) ;
El ement pubDat e = ( El ement ) ent r y. get El ement sByTagName(
" pubDat e" ) . i t em( 0) ;
El ement l i nk = ( El ement ) ent r y. get El ement sByTagName(
" l i nk" ) . i t em( 0) ;

St r i ng t i t l eVal ue = t i t l e. get Fi r st Chi l d( ) . get NodeVal ue( ) ;
St r i ng descr i pt i onVal ue =descr i pt i on. get Fi r st Chi l d( ) . get NodeVal ue( ) ;
St r i ng dat eVal ue = pubDat e. get Fi r st Chi l d( ) . get NodeVal ue( ) ;
St r i ng l i nkVal ue = l i nk. get Fi r st Chi l d( ) . get NodeVal ue( ) ;

Si ngl eNewsI t emsi ngl eI t em= new SingleNewsItem(
dat eVal ue, t i t l eVal ue, descr i pt i onVal ue, l i nkVal ue) ;
newsLi st . add( si ngl eI t em) ;

} catch (DOMException e) {
e. pr i nt St ackTr ace( ) ;
}
}/ / di ssect Node


41
18. Android Internet Feeders

Internet
41
Activity2: NPRNewsDetails.java cont



public void showNiceDialogBox(SingleNewsItem selectedNewsItem, Cont ext cont ext ) {
/ / assembl e a ni ce l ooki ng di al og box
try {
final Uri myLink = Uri.parse(selectedNewsItem.getLink());
Al er t Di al og. Bui l der myBui l der = new AlertDialog.Builder(this);
myBui l der
. set I con( R. dr awabl e. logo_npr)
. set Ti t l e( ur l Capt i on)
. set Message( sel ect edNewsI t em. get Ti t l e( ) + " \ n\ n"
+ sel ect edNewsI t em. get Descr i pt i on( ) + " \ n" )
. set Posi t i veBut t on( " Cl ose" , null)
. set Negat i veBut t on( " Mor e" , new OnClickListener() {

public void onClick(DialogInterface dialog, int whichOne) {
/ / use nat i ve web br owsi ng
I nt ent webI nt ent = new Intent( I nt ent . ACTION_VIEW, myLink) ;
st ar t Act i vi t y( webI nt ent ) ;
}
}) / / set Negat i veBut t on
. show( ) ;
} catch (Exception e) {
e. pr i nt St ackTr ace( ) ;
}
}/ / showNi ceDi al ogBox

}/ / Npr NewsDet ai l s
42
18. Android Internet Feeders

Internet
42
Class: SingleNewsItem.java



package matos.internet;

public class SingleNewsItem {
private String pubDate;
private String title;
private String description;
private String link;

public String getPubDate() { return pubDate; }
public String getTitle() { return title;}
public String getDescription(){ return description; }
public String getLink() { return link; }

public SingleNewsItem( String _pubDate, String _title, St r i ng _descr i pt i on,
St r i ng _l i nk) {
pubDat e = _pubDat e;
descr i pt i on = _descr i pt i on;
t i t l e = _t i t l e;
l i nk = _l i nk;
}

@Over r i de
public String toString() {
return title;
}
}
43
18. Android Internet Feeders

Internet
43
manifest


<?xml ver si on="1.0" encoding="utf-8"?>
<mani f est xml ns: andr oi d="http://schemas.android.com/apk/res/android"
package="matos.internet"
andr oi d: ver si onCode="1"
andr oi d: ver si onName="1.0.0">
<appl i cat i on andr oi d: i con="@drawable/star_big_on" android:label="@string/app_name">

<act i vi t y andr oi d: name=".AndroNPR"
andr oi d: l abel ="@string/app_name">
<i nt ent - f i l t er >
<act i on andr oi d: name="android.intent.action.MAIN" />
<cat egor y andr oi d: name="android.intent.category.LAUNCHER" />
</ i nt ent - f i l t er >
</ act i vi t y>

<act i vi t y andr oi d: name=".NprNewsDetails" >
</ act i vi t y>

</ appl i cat i on>

<uses- per mi ssi on andr oi d: name="android.permission.INTERNET"/>
<uses- sdk andr oi d: mi nSdkVer si on="4" />

</ mani f est >
44 44
18. Android Internet
Internet
44


Questions

You might also like