Android Development Crawl News case

Source: Internet
Author: User

I. Overview
this is a Crawl Web news through HttpClient the demo. Related to the knowledge point: Through the httpclient from the network to obtain news (organized into XML format), pull parsing xml,android under the use and optimization of the ListView, the XML resource file into the view display, Android simple layout, Android message processing mechanism. The Web page news used here is simulated using new.xml in a Web application under Tomcat, and the virtual machine access to this machine can be accessed via the following link: http://10.0.2.2:8080/app name/new.xml.

Second, step

Here's the idea: Wrap news content in JavaBean ( news content includes images, titles, details, number of threads ), and when activity is created, Open a sub-thread to access network resources (because Android4.0 does not support the main thread to access network resources later, it throws an exception:


)。 Parse the resulting XML file, traverse the node to get news information and encapsulate the bean into the collection, send this collection through a message to the main thread of the handler object to process (only the main thread can modify the user interface), and then customize an adapter, Adds the content of the news bean to the specified control, specifying the current adapter for the ListView to display the news.

The main code is divided into the following sections:

1. Getting an input stream of an XML file from the network

/** * Get news input stream from the network * The List collection consisting of @return news bean */protected list<newsinfo> getnewsfromintenet () {HttpClient client = nul L;try {//define a client = new defaulthttpclient (); HttpGet get = new HttpGet ("Http://10.0.2.2:8080/Example/new.xml");//access network resource HttpResponse response = Client.execute (GET) ///Execute GET request to get response int code = Response.getstatusline (). Getstatuscode ();//Get Status code if (code = = 200) {//request succeeded, get data and return InputStream in = Response.getentity (). getcontent ();//get content input Stream newslist = Getnewslistfrominputstream (in);//Specify Xmlreturn based on flow resolution newslist;//returns a list collection consisting of news beans}else{//request failed, print log log.i (tag, "request failed, check code" + Codes);}} catch (Exception e) {e.printstacktrace ();} Finally{if (client! = null) {Client.getconnectionmanager (). shutdown ();//Close client resource}}return null;}

2. By parsing XML file Gets a list of news beans

/** * Parse from XML newslist * @return News Collection * @throws Exception */private list<newsinfo> getnewslistfrominputstream (I Nputstream in) throws Exception {Xmlpullparser parser = Xml.newpullparser ();//Create a pull parser for parsing Xml parser.setinput (in, " Utf-8 "); int eventtype = Parser.geteventtype ();//Get event type list<newsinfo> list = null; Newsinfo newsinfo = Null;while (eventtype! = xmlpullparser.end_document) {String tagName = Parser.getname ();// Gets the label name Switch (eventtype) {case xmlpullparser.start_tag://setting specifies the content if ("News". Equals (TagName)) {list = new arraylist< Newsinfo> ();} else if ("new". Equals (TagName)) {newsinfo = new Newsinfo ();} else if ("title". Equals (TagName)) {Newsinfo.settitle (Parser.nexttext ());} else if ("detail". Equals (TagName)) {Newsinfo.setdetail (Parser.nexttext ());} else if ("comment". Equals (TagName)) {newsinfo.setcomment (integer.valueof (Parser.nexttext ()));} else if ("image". Equals (TagName)) {Newsinfo.setimage (Parser.nexttext ());} Break;case XmlPullParser.END_TAG:if ("New". Equals (TagName)) {//A new end,Add the encapsulated news bean to the collection List.add (Newsinfo);} Break;default:break;} EventType = Parser.next ();//Remove an event type}return list;}

3. Send the acquired information to handler via a message

/** * Initialize the operation, open a new thread to get the resource */public void init () {lvnews = (ListView) Findviewbyid (r.id.lv_news);//Find the Listviewnew Th used to display the news Read (new Runnable () {///open a thread to access network resources @overridepublic Void Run () {list<newsinfo> newslist = Getnewsfromintenet (); Message msg = new Message (); if (newslist! = null) {Msg.what = success;//Specifies the message type msg.obj = Newslist;} Else{msg.what = FAILED;} Handler.sendmessage (msg);//Send Message}}). Start ();//Open Thread}

4.Handler is handled according to the message type: List is empty prompt error, not null display information on the ListView through the adapter

<span style= "color: #ff0000;" ></span>public view GetView (int position, view Convertview, ViewGroup parent) {view view = null; Viewholder holder = null;if (Convertview = = null) {holder = new Viewholder (); view = View.inflate (Mainactivity.this, r.layou T.layout_news_list, NULL); Smartimageview Sivicon = (smartimageview) View.findviewbyid (r.id.image); Sivicon.setimageurl (NewsList.get (position) . GetImage ());//Set Picture Holder.tv_title = (TextView) View.findviewbyid (r.id.tv_title); Holder.tv_title.setText ( Newslist.get (position). GetTitle ()) Holder.tv_comment = (TextView) View.findviewbyid (r.id.tv_comment); holder.tv_ Comment.settext (Newslist.get (position) getcomment () + "thread"); holder.tv_detail = (TextView) View.findviewbyid (r.id.tv _detail); Holder.tv_detail.setText (Newslist.get (position) getdetail ()); View.settag (holder);// Add a member variable from the holder object to view}else{view = Convertview;holder = (viewholder) View.gettag ();} return view;}} /** * Used to optimize the reuse of view classes */class viewholder{public TextView tv_title;public TextViewTv_detail;public TextView tv_comment;public ImageView iv_image;} 

Be aware of:

There are three ways to convert an XML resource file into a view, and the underlying implementation is the same, as in this case: view = View.inflate (mainactivity.this, r.layout.layout_news_list, NULL);

When optimizing a ListView, you can reduce the number of views created by reusing Convertview, and further, you can declare a control in a view as a member by defining a class, such as the Viewholder class above.

Finally, the previous bar:


Android Development Crawl News case

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.