First of all, we need to analyze the layout of NetEase RSS Subscription Center page.
NetEase RSS Subscription Center: http://www.163.com/rss/
You will find that the RSS file consists of a <channel> element and its child elements, in addition to the contents of the channel itself,,<channel> also contains elements that represent the channel metadata in the form of an item.
The main three elements below 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: A brief description of what the channel does.
Of course, there are other sub-elements are optional, such as commonly used <image>,<language>,<copyright><pubDate> and so on.
The RSS reader We've written below is comprised of four elements, with titile,link,description,pubdate.
First: We create a news entity class:
Package Com.example.rssview;
public class News {
Private String title;//News Headlines
Private String link;//News URL
Private String description;//News description
Private String pubdate;//Press 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;
}
}
Above is the first step in the development of the program, complete the creation of the entity class
The second step: we should also be able to imagine, must parse XML useful data, commonly used parsing XML method has three kinds: Dom parsing, sax parsing, pull parsing
Because DOM parsing must read all the XML content into memory, it consumes system resources, so I recommend choosing Sax parsing, or pull parsing.
Here I choose the Sax parsing method specific code 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 the parsed news data
Private news news;//Single press content
Private String nodename;//is judged by that element with
Get all news data
Public list<news> getnewslist () {
return newslist;
}
Start parsing 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;
}
Ends 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 ());
}
}
Parsing the text content of an 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 have to explain more, I believe that the comments have been very detailed, but also provides a method for external access to parse data getnewslist ();
The third step: Of course, go to the activity to write the main code
At first we must prepare the 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, which makes it easier to program
You should also know that this is to get the XML data from the network read URL, according to the programming principle of Android, the time consuming network operation should not be executed directly in the main thread, because this will cause the main thread to crash.
However, Android provides us with an asynchronous processing mechanism class Asynctask as long as you write a class to implement the class to put the time-consuming task in the Doinbackground method to deal with it.
When we get the network data, we manipulate the update UI to display the parsed XML data, which can be solved in Asynctask's onpostexecute.
Perhaps we should also analyze the Asynctask three parameters, the first parameter is passed in the parameters, such as we will pass in a URL for Asynctask parse to get the XML data, the second parameter is the progress display units we often set to integer, The third parameter is the data returned by the Doinbackground method for OnPostExecute calls, which is the OnPostExecute parameter.
Below we must first obtain the XML of the network.
URL url = null;//Create URL object
String xmlsourcestr = null;//parsed XML data
try {
url = new URL (params[0]);//Get the URL resource passed in
if (URL! = null) {
HttpURLConnection conn = (httpurlconnection) URL
. OpenConnection ();//Open link
InputStreamReader Isreader = new InputStreamReader (
Conn.getinputstream (), "UTF-8");//Read the data into the InputStreamReader object and set the encoding format to UTF-8
BufferedReader br = new BufferedReader (isreader);//Instancing BufferedReader
StringBuilder sb = new StringBuilder ();
String line = null;
while (line = Br.readline ()) = null) {
Sb.append (line);//Read XML data into StringBuilder
}
Isreader.close ();//Turn off Data flow
Conn.disconnect ();//close connection
Xmlsourcestr = Sb.tostring ();//read StringBuilder data into a string
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Return xmlsourcestr;//returns parsed XML string data
This method belongs to the network processing more time-consuming, I believe everybody also knew, should write in Doinbackground
After getting the XML data for the network, here is the data that parses the XML, as mentioned above. The parsing method we use is Sax parsing. The code is as follows:
SAXParserFactory factory = Saxparserfactory.newinstance ();//Create SAXParserFactory instance
if (result! = null) {
try {
SAXParser parser = Factory.newsaxparser ();//new SAXParser parsing class
XMLReader XMLReader = Parser.getxmlreader ();//create XMLReader Read class
Saxparserhelper helper = new Saxparserhelper ();//instantiation of Sax parsing method
Xmlreader.setcontenthandler (helper);//Set processor
Xmlreader.parse (new InputSource (result));//Read data to be processed
Newslist = Helper.getnewslist ();//Get processed results
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
The above operation is not part of the network because the lantern needs to operate the update UI, so the code is written in OnPostExecute
Below we use the iterator to traverse the result of the processing, of course need to judge to obtain the desired result no, the code is as follows:
if (!newslist.isempty ())
Iterator<news> it = Newslist.iterator ();
Then create a Map class to accept the traversal results map<string,object> map=new hashmap<string,object> ();
And Simpleadapter's constructor receives a list object, and each Map you get above is just a separate news, so you have to create a list<map<string,object>> newslist= New arraylist<map<string,object>> (); Keep each Map news in Newslist.
For just said Simpleadapter generally have a little bit of Android Foundation should be not unfamiliar, yes he is simple adapter. It will be necessary to display the data to the ListView.
Now let's set the ListView to display the news with the following code:
Bind the ListView interface first
Simpleadapter adapter=new Simpleadapter (Context,list object, layout file, data item in ListView, data item in ListView, corresponding ID);
The first parameter is not unfamiliar is the context, simply said to inherit the class name of the activity. this.
The second parameter belongs to the newslist that was just getting all the news.
The third parameter is the layout file style r.layout that the ListView will display. Your layout filename.
The fourth parameter is the name of the preceding string in the Map.put method.
The fifth parameter is the ID of each item in the third parameter layout file that is used to display the news;
Finally set to the ListView, the specific 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 show the news detailed content display function, but I believe that after reading the above code, you also know that setting the display news believe content and get the above code is similar to the wonderful.
Well, that's what the simple RSS reader says. My first blog post, though imperfect, is a starting point for explaining the program.
NetEase News RSS Reader