Android application of "Song CI 300" (a)

Source: Internet
Author: User
Tags cdata

Today we use a practical case to synthesize the knowledge of all aspects of Android technology, imitate "song CI 300" Write an application, the code all the resources are from the Internet, only for learning, do not for commercial purposes.

(1) The first step to create a new Android project, modify the app icon, copy the 72x72 app icon to the drawable-hdpi folder, copy the 96x96 app icon to the drawable-xhdpi folder, Then modify the contents of the Androidmanifest.xml file as follows:

<application        android:icon= "@drawable/icon"

Then modify the contents of the Strings.xml as follows:

<string name= "App_name" > Song ci 300 </string>    <string name= "Title_activity_main" > Song ci 300 first </string >

Modify the app name to modify the contents of the Androidmanifest.xml file as follows:

Android:label= "@string/app_name"        android:theme= "@style/apptheme" >        <activity            android:name= ". Ui. Splashactivity "            android:label=" @string/title_activity_main ">

After the above work, the app's icon and name have been modified OK;

(2) Let's write the first interface: Welcome interface

First copy the background image welcome.jpg to drawable-hdpi below, then create a new activity_splash.xml below the layout folder, as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical"     android:background= "@drawable/welcome" >    </LinearLayout>

Then create a new Splashactivity.java file under SRC, the code has been commented in detail, the following:

Package Com.example.songcidemo.ui;import Com.example.songcidemo.r;import Android.app.activity;import Android.content.intent;import android.os.bundle;import android.os.handler;import android.view.Window;/** *app Welcome Screen * /public class Splashactivity extends Activity {/** * The first callback method executed at startup */@Overrideprotected void onCreate (Bundle savedinstance State) {super.oncreate (savedinstancestate);//Setup interface without title bar requestwindowfeature (window.feature_no_title);// Specifies the layout file for the interface Setcontentview (R.layout.activity_splash);//Initializes a handlerhandler handler = new handler ();//runnable is a thread, Executes the thread object after 1500 milliseconds handler.postdelayed (new Runnable () {@Overridepublic void Run () {// Jump from splashactivity to mainactivityintent intent = new Intent (splashactivity.this, Mainactivity.class); StartActivity ( intent);//closed SplashActivitySplashActivity.this.finish ();}},  1500);}}

operating effects such as:


(2) Then we write the second interface, before we write the second interface, we need to do some preparatory work, that is, to prepare the data, all the data are stored in a file such as Songci.xml, here I intercept a bit of the fragment as follows:

<?xml version= "1.0" encoding= "UTF-8" standalone= "no"? ><root><node><title><! [Cdata[-dong Fairy song • Si Zhou mid-Autumn Festival as]]></title><auth><! [Cdata[Chao complement the]]></auth><desc><! [cdata[<p> Si Zhou ① mid-Autumn Festival make </p> <p> <strong> Chao, </strong> </p> <p> Green Smoke power ② place, blue sea fly golden. Yong-night Leisure order lying GUI. </p> <p> Cold, messy how many cold 螀 ③, God ④ far, only Blue Bridge ⑤ road near. </p> <p> Crystal Curtain, Mica screen ⑥ open, cold dip ⑦ light powder. </p> <p> will be many Ming, paid the king, cast Xiao Total, flow xia ⑧ pour. </p> <p> more carry, Hu bed ⑨ on the south floor, see Jade Man between, vegetarian swing tilt. </p> <p><br/> "notes" <br/>① si Zhou: Anhui Si County. </p> <p>② Power (mì): Cover. </p> <p>③ Cold 螀 (Jiāng): Chilling. </p> <p>④: Refers to the Northern Song Dynasty capital Bianliang. </p> <p>⑤ Blue Bridge: In the southeast of Shaanxi Lantian County, the bridge is above the blue water, hence the name. Musicians its land has fairy cave, Tang Pai meet greisenized in this bridge. </p> <p>⑥ Yun: Mica is the main component of granite, can be used as a screen, bright luster. </p> <p>⑦: Here refers to the women at the dinner </p> <p>⑧ Stream Xia: The name of the wine. Semantic pun, refers to wine, also refers to the Sunrise </p> <p>⑨: A light seating in ancient times, can be folded. </p> <p> "translation" <br/> Cyan Smoke, covering the shadow of the moon, from the clear sea-like Sky flew a golden mirror. The long night on the empty steps of hanging trees on the oblique shadow. When the night dew fades away, manyLess autumn cicada scattered voice Miss Kyoto road far, on the road near only have the Moon Palace Wonderland, High-volume crystal curtain, expand mica screen, beauty of light powder infiltration of the night months of cold. To me many moonlight, pour into the golden bottle, until the dawn with the stream chardonnay all pour out. Then carry a king Hu bed boarded the South building, see the white Jade paved into the world, appreciate the Bai Shunji clear autumn. </p>]]></desc></node>

we put Songci.xml under the assets folder, because the XML file is a bit large, when packaged into an APK file will be compressed, resulting in the read time generated IOException, more details on this issue refer to IOException while Reading from InputStream, so we will rename the Songci.xml file to Songci.mp3 to avoid such problems.


Second is the preparation of a few knowledge points (if you are already familiar with this knowledge, please skip):

Sax parsing xml

Pull parsing xml

So let's start parsing and encapsulating the XML data:

First create an interface Isongciparser, which reads as follows:

Package Com.example.songcidemo.data;import Java.io.inputstream;import Java.util.list;import Com.example.songcidemo.bean.songci;public interface Isongciparser {/** * parse XML input stream *  * @param is input stream * @param sclist load capacity * @throws Exception */public void Parse (InputStream is,list<songci> sclist) throws Exception;}

Here is a little bit of code to write the problem: Because previously wanted to use the SAX parser to parse XML, but half of the time to find that the problem is that the content between <desc></desc> contains a lot of <p></p> <strong></strong><br></br> such a label pair, sax parsing when the contents are used as element for the partition to get the value, but I want to beall content between <desc></desc> as a value, so use sax to do half of the time decisively instead of using the pull parser to parse, the resolution is smooth, there is no problem. Go on ...

Then we write a pull parsing implementation class Songciparserimpl, which reads as follows:

Package Com.example.songcidemo.data;import Java.io.inputstream;import Java.util.list;import Org.xmlpull.v1.xmlpullparser;import Android.util.xml;import Com.example.songcidemo.bean.songci;public Class Songciparserimpl implements isongciparser{//defines XML file label constants with constant values consistent with label names in XML files private static final String Tag_node = "NODE"; private static final String tag_title = "TITLE";p rivate static final String tag_auth = "AUTH";p rivate static final string Tag_desc = "DESC";/** * method of parsing XML file * * is input stream * sclist load data is parsed and encapsulated into SONGCI list */@Overridepublic void Parse (InputStream is, L Ist<songci> sclist) throws Exception {Songci sc = null;if (sclist! = null) {sclist.clear ();} Gets the Xmlpullparser instance xmlpullparser xpp = Xml.newpullparser ();//sets the input stream for the Xmlpullparser instance and sets the character set of the input stream to Utf-8xpp.setinput ( IS, "utf-8");//Gets the type of the current event, such as start_tag,end_tag,text, etc. int eventtype = Xpp.geteventtype ();// If the type of the current time is not the end of the file, execute the Loop while (eventtype! = xmlpullparser.end_document) {switch (eventtype) {case Xmlpullparser.start_ Document://do nothingbreak;//If the current event type is the start element case XmlPullParser.START_TAG:if (Xpp.getname (). Equals (Tag_node)) {//If you encounter <node> create a new SONGCI object SC = new Songci ();} else if (Xpp.getname () equals (Tag_title)) {//If you encounter <title> will pass <title> text to Scsc.settitle (xpp.nexttext ());} else if (Xpp.getname () equals (Tag_auth)) {//If you encounter <auth> will pass <auth> text to Scsc.setauth (Xpp.nexttext ());} else if (Xpp.getname () equals (Tag_desc)) {//If you encounter <desc> will pass <desc> text to Scsc.setdesc (Xpp.nexttext ());} Break;case XmlPullParser.END_TAG:if (Xpp.getname (). Equals (Tag_node)) {//If you encounter </node> The object associated with SC is added to the list Sclist.add (SC); sc = null;} Break;default:break;} Enter the next element and trigger the corresponding event EventType = Xpp.next ();}}}

With this step written, we can use it directly in the activity, and in mainactivity I've commented out the sax part, and the rest of the code is commented in detail, as follows:

Package Com.example.songcidemo.ui;import Java.io.inputstream;import Java.util.arraylist;import Javax.xml.parsers.saxparser;import Javax.xml.parsers.saxparserfactory;import Org.xml.sax.InputSource;import Org.xml.sax.xmlreader;import Android.app.activity;import Android.content.intent;import Android.content.res.assetmanager;import Android.os.bundle;import Android.view.view;import Android.view.Window; Import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.listview;import Com.example.songcidemo.r;import Com.example.songcidemo.bean.songci;import Com.example.songcidemo.data.mainlistviewadapter;import Com.example.songcidemo.data.songciparserimpl;import Com.example.songcidemo.data.songcisaxhandler;import Com.example.songcidemo.util.global;public class MainActivity Extends Activity {//declares a list of loaded SONGCI types private arraylist<songci> sclist;//declares a ListView variable private listview    Mlistview; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_main);        InitData ();//Saxparsexml ();        Pullparsexml ();            Setupviews ();    } private void InitData () {//Initialize sclist sclist = new arraylist<songci> (); /** * Parse XML file with SAX parser */private void Saxparsexml () {try {//Get a Assetmanager object Assetmanager a    Ssetmanager = This.getassets ();        The input stream InputStream InputStream = Assetmanager.open ("Songci.mp3") to Songci.mp3 is obtained through the Assetmanager open method;        Encapsulate the contents of the InputStream into InputSource inputsource inputsource = new InputSource (InputStream);        Get SAXParserFactory instance SAXParserFactory saxparserfactory = Saxparserfactory.newinstance ();        Gets the SAXParser object saxparser saxparser = Saxparserfactory.newsaxparser ();        Gets the XMLReader object XMLReader XMLReader = Saxparser.getxmlreader (); Initialize Scsaxhandler        Songcisaxhandler Scsaxhandler = new Songcisaxhandler (sclist);        Pass the Scsaxhandler to XmlReader Xmlreader.setcontenthandler (Scsaxhandler);                Start parsing xml file Xmlreader.parse (InputSource);                Close flow inputstream.close ();        } catch (Exception e) {e.printstacktrace ();} }/** * Parse XML file with pull method */private void Pullparsexml () {try {InputStream is = This.getassets (). Open ("s Ongci.mp3 "); Songciparserimpl SCPI = new Songciparserimpl (); Scpi.parse (is, sclist);}    catch (Exception e) {e.printstacktrace ();}        }/** * Initialize view */private void Setupviews () {Mlistview = (ListView) Findviewbyid (R.id.lv_catelog); Initializes an instance of the custom type Mainlistviewadapter adapter, passing sclist to adapter's constructor Mainlistviewadapter adapter = new Mainlistviewadapte        R (this, sclist);        Pass the adapter to Mlistview Mlistview.setadapter (adapter); Mlistview.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void onitemcliCK (adapterview<?> parent, View view,int position, long id) {GLOBAL.CURRENTSONGCI = Sclist.get (position); Intent    Intent = new Intent (mainactivity.this, Contentactivity.class); startactivity (intent);}}); }}

Because there is a custom adapter, so here is the definition of mainlistviewadapter, convenient for everyone to read: (This class I did not add comments, if the reader is feeling difficult to read, it is recommended to first look at this article custom listview)

Package Com.example.songcidemo.data;import Java.util.arraylist;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.textview;import Com.example.songcidemo.r;import Com.example.songcidemo.bean.songci;public class Mainlistviewadapter extends Baseadapter{private ArrayList<SongCi > Sclist;private Context context;public mainlistviewadapter (context context, arraylist<songci> sclist) { This.context = Context;this.sclist = sclist;} @Overridepublic int GetCount () {return sclist.size ();} @Overridepublic Object getItem (int position) {return sclist.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Listviewitemholder holder;if ( Convertview = = null) {Layoutinflater Inflater = layoutinflater.from (context); Convertview = Inflater.inflate ( R.layout.list_item, NULL); holder = new Listviewitemholder (); Holder.titletextview = (TextView) Convertview.findviewbyid (r.id.tv_title); Holder.authtextview = (TextView) Convertview.findviewbyid (R.id.tv_auth); Convertview.settag (holder);} Else{holder = (Listviewitemholder) Convertview.gettag ();} SONGCI sc = sclist.get (position); String title = Sc.gettitle (); String auth = Sc.getauth (); Holder.titleTextView.setText (title); Holder.authTextView.setText (auth); return Convertview;} Private class Listviewitemholder{textview Titletextview; TextView Authtextview;}}

Attach a mainactivity interface:


More content, tell ...


Android application of "Song CI 300" (a)

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.