Netease News RSS reader and Netease News rss
First, we need to analyze the web page layout of the Netease RSS subscription center.
Netease RSS subscribe center: http://www.163.com/rss/
You will find that the RSS file is composed of a <channel> element and its sub-elements. In addition to the content of the channel itself, <channel> also contains elements that represent the channel metadata in the form of items.
The main three elements of the channel are:
1. title: the name of the channel or feed.
2. link: the URL of the WEB site or site area associated with the channel.
3. description: briefly introduces what the channel is.
Of course, other sub-elements are optional, such as <image>, <language>, and <copyright> <pubDate>.
The following RSS reader contains four elements: titile, link, description, and pubDate.
First, we create the news entity class:
Package com. example. rssview;
Public class News {
Private String title; // news title
Private String link; // news URL
Private String description; // news description
Private String pubDate; // news release time
Public News (){
}
Public News (String title, String link, String description, String pubDate ){
This. title = title;
This. link = link;
This. description = description;
This. pubDate = pubDate;
}
Public String getTitle (){
Return title;
}
Public void setTitle (String title ){
This. title = title;
}
Public String getLink (){
Return link;
}
Public void setLink (String link ){
This. link = link;
}
Public String getDescription (){
Return description;
}
Public void setDescription (String description ){
This. description = description;
}
Public String getPubDate (){
Return pubDate;
}
Public void setPubDate (String pubDate ){
This. pubDate = pubDate;
}
}
The above is the first step in program development to complete the creation of object classes.
Step 2: we can imagine that we must parse useful XML data. There are three common methods for parsing XML: DOM parsing, SAX parsing, and PULL parsing.
DOM parsing must read all XML content into the memory, which consumes system resources. Therefore, we recommend using SAX or PULL parsing.
The specific code for selecting the SAX parsing method is as follows:
Package com. example. rssview;
Import java. util. ArrayList;
Import java. util. List;
Import org. xml. sax. Attributes;
Import org. xml. sax. SAXException;
Import org. xml. sax. helpers. DefaultHandler;
Import android. util. Log;
Public class SAXParserHelper extends DefaultHandler {
Private List <News> newsList; // save all parsed News data
Private News news; // a single News content
Private String nodeName; // determines which element is used
// Obtain all news data
Public List <News> getNewsList (){
Return newsList;
}
// Start parsing the XML document
@ Override
Public void startDocument () throws SAXException {
NewsList = new ArrayList <News> ();
}
// End parsing XML document
@ Override
Public void endDocument () throws SAXException {
// TODO Auto-generated method stub
Super. endDocument ();
}
// Start parsing an element
@ Override
Public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
If (localName. equals ("title ")){
News = new News ();
}
This. nodeName = localName;
}
// End parsing an element
@ Override
Public void endElement (String uri, String localName, String qName)
Throws SAXException {
If (localName. equals ("item ")){
NewsList. add (news );
// Log. I ("SAXParserHelper", news. getTitle ());
// Log. I ("SAXParserHelper", news. getLink ());
// Log. I ("SAXParserHelper", news. getPubDate ());
// Log. I ("SAXParserHelper", news. getDescription ());
}
}
// Parse the text content of the element
@ Override
Public void characters (char [] ch, int start, int length)
Throws SAXException {
If ("title". equals (this. nodeName )){
News. setTitle (String. valueOf (ch, start, length ));
} Else if ("link". equals (this. nodeName )){
News. setLink (String. valueOf (ch, start, length ));
} Else if ("description". equals (this. nodeName )){
News. setDescription (String. valueOf (ch, start, length ));
} Else if ("pubDate". equals (this. nodeName )){
News. setPubDate (String. valueOf (ch, start, length ));
}
}
}
The Code does not need to be explained much. I believe the remarks are already very detailed, and the getNewsList () method is also provided for external users to obtain the parsed data ();
Step 3: Write the main code in the Activity.
At first, we must prepare a layout file containing the listView control, and then set the layout file in the activity.
Of course, you can also directly inherit the ListActivity class to facilitate programming.
You should also know that this is to read XML data from the Web site. According to Android programming principles, time-consuming network operations should not be directly executed in the main thread, because this will cause the main thread to crash.
However, android provides us with an asynchronous processing mechanism class AsyncTask. You only need to write a class to implement this class to put time-consuming tasks in the doInBackground method for processing.
After obtaining the network data, we will update the UI to display the parsed XML data. This can be solved in onPostExecute of AsyncTask.
Maybe we should also analyze the three parameters of AsyncTask. The first parameter is the passed parameter. For example, we will input a URL for AsyncTask to parse and obtain XML data, the second parameter is the progress display unit. We often set it to Integer. The third parameter is the data returned by the doInBackground Method for onPostExecute to call, that is, the onPostExecute parameter.
Next, we must first obtain the XML of the network.
URL url = null; // create a URL object
String XmlSourceStr = null; // XML data after Parsing
Try {
Url = new URL (params [0]); // obtain the url resource passed in
If (url! = Null ){
HttpURLConnection conn = (HttpURLConnection) url
. OpenConnection (); // open the link
InputStreamReader isReader = new InputStreamReader (
Conn. getInputStream (), "UTF-8"); // read data to the InputStreamReader object and set the encoding format to UTF-8
BufferedReader br = new BufferedReader (isReader); // instantiate bufferedReader
StringBuilder sb = new StringBuilder ();
String line = null;
While (line = br. readLine ())! = Null ){
Sb. append (line); // read XML data to StringBuilder
}
IsReader. close (); // close the data stream
Conn. disconnect (); // close the connection
XmlSourceStr = sb. toString (); // read StringBuilder data to the string
}
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Return XmlSourceStr; // return the parsed XML string data
This method is time-consuming for network processing. As you may know, it should be written in doInBackground.
After obtaining the XML data of the network, the XML data is parsed as mentioned above. The parsing method we use is SAX parsing. The Code is as follows:
SAXParserFactory factory = SAXParserFactory. newInstance (); // create a SAXParserFactory instance
If (result! = Null ){
Try {
SAXParser parser = factory. newSAXParser (); // creates a SAXParser parsing class.
XMLReader xmlReader = parser. getXMLReader (); // create an XMLReader read class
SAXParserHelper helper = new SAXParserHelper (); // instantiate the SAX Parsing Method
XmlReader. setContentHandler (helper); // sets the processor
XmlReader. parse (new InputSource (new StringReader (result); // read the data to be processed
NewsList = helper. getNewsList (); // obtain the processing result
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
The above operation does not belong to the network because the lamp will need to update the UI, so the code is written in onPostExecute
Next we will use the iterator to traverse the processing results. Of course, we need to determine whether the expected results are obtained. The Code is as follows:
If (! NewsList. isEmpty ())
Iterator <News> it = newsList. iterator ();
Then create a Map class Map <String, Object> map = new HashMap <String, Object> () for receiving the traversal results ();
The simpleAdapter constructor receives a List object, and each map obtained above is just a separate news. Therefore, you must create a List <Map <String, object> newsList = new ArrayList <Map <String, Object> (); stores each map news in newsList.
For simpleAdapter, there should be no stranger to the android basic. Yes, it is a simple Adapter. It will display the data to the listView.
Now let's set the listView to display news. The Code is as follows:
First bind the listView Interface
SimpleAdapter adapter = new SimpleAdapter (Context, list object, layout file, data item in listView, ID of the data item in listView );
The first parameter is no stranger to context. Simply put, it is to inherit the Class Name of the activity. this.
The second parameter belongs to the newsList that just obtained all news.
The third parameter is the layout file style R. layout to be displayed by listView. Your layout file name.
The fourth parameter is the name of the string in the map. put method.
The fifth parameter is the ID of each item used to display news in the third parameter layout file;
The Code is as follows:
If (! NewsList. isEmpty ()){
Iterator <News> it = newsList. iterator ();
While (it. hasNext ()){
News news = (News) it. next ();
HashMap <String, Object> map = new HashMap <String, Object> ();
Map. put ("title", news. getTitle ());
Map. put ("pubDate", news. getPubDate ());
Log. I ("MainActivity", news. getTitle ());
Log. I ("MainActivity", news. getPubDate ());
MData. add (map );
}
SimpleAdapter adapter = new SimpleAdapter (MainActivity. this,
MData, R. layout. list_item, new String [] {"title ",
"PubDate"}, new int [] {R. id. title,
R. id. pubDate });
NewsListView. setAdapter (adapter );
}
Of course, I did not display the detailed content of the news here, but I believe that after reading the above Code, you also know that setting news, believing content, and getting the above Code are just the same.
Well, this is the simple RSS reader. My first blog is not perfect, but it is also a starting point for explaining the program.