Generating an XML file from the XmlSerializer interface

Source: Internet
Author: User

XML files We can use to save some data. For example, to back up text messages. In this example, we use the XmlSerializer interface to implement a backup SMS program. Of course, in order to simplify the program, this program we are not really to back up text messages. We use a Message.java file as a javabean. Use him to virtual a text message class. Then we'll back up the virtual content.

After the backup, an XML file is generated in the corresponding directory. We can use the browser to open, parse out the XML to see.

Look at the program run effect first.

Then we looked directly at the code, and by the right, I didn't get the list file. The manifest file is nothing, because you want to write files to the SD card, so add a permission to write to the SD card

    <android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Following the XML file I generated, after running the program, the SD card will be generated under the root directory info.xml files. Here is the effect I resolved after I opened it with a browser.

See the code below

The first is the layout file

<Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.example.savexml.MainActivity" >    <ButtonAndroid:id= "@+id/bt"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "@string/hello_world" /></Relativelayout>

Then the Java file (two classes)

The first is Message.java (the role of this class is mainly used for texting, as the role of JavaBean)

 PackageCom.example.savexml; Public classMessage {//Define SMS Content    PrivateString body; //Define SMS Date    PrivateString date; //Define Sender Number    PrivateString address; //defining send and receive types    PrivateString type;  PublicString GetBody () {returnbody; }     Public voidSetbody (String body) { This. BODY =body; }     PublicString getDate () {returndate; }     Public voidsetDate (String date) { This. Date =date; }     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; }     PublicString GetType () {returntype; }     Public voidsetType (String type) { This. Type =type; }     PublicMessage (string body, string date, string address, String type) {Super();  This. BODY =body;  This. Date =date;  This. Address =address;  This. Type =type; }}

And then the mainactivity.

 PackageCom.example.savexml;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.xmlpull.v1.XmlSerializer;Importandroid.app.Activity;ImportAndroid.os.Bundle;Importandroid.os.Environment;ImportAndroid.util.Log;Importandroid.util.Xml;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {List<Message>smslist; PrivateButton Btbutton; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //collection of text messages storedSmslist =NewArraylist<message>(); //Virtual 20 SMS         for(inti = 0; I <= 20; i++) {Message MSM=NewMessage ("Message content" +I, System.currenttimemillis ()+ "", "10086", "1");        Smslist.add (MSM); } Btbutton=(Button) Findviewbyid (R.ID.BT); Btbutton.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method Stub                Try{backup (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace ();    }            }        }); }    Private voidBackup ()throwsIOException {//get the XML serializerXmlSerializer xs =Xml.newserializer (); //Packaging External storage pathsFile File =NewFile (Environment.getexternalstoragedirectory (),"Info.xml"); FileOutputStream Fos=NULL; Try {            //output info.xml with output streamFOS =Newfileoutputstream (file); //specify to generate files with Utf-8 encodingXs.setoutput (FOS, "Utf_8"); //generates an XML header with two parameters representing the header propertiesXs.startdocument ("UTF-8",true); //Build root node            /** In fact, the process of splicing is a bit like writing HTML files, nothing more than a pair of tags, a pair of label writing.             * From the code can be seen, Xs.starttag (), indicating the beginning of the label, Endtag () indicates the end of the label.             * The second parameter indicates the name of the node. */Xs.starttag (NULL, "message");  for(Message sms:smslist) {Xs.starttag (NULL, "SMS"); Xs.starttag (NULL, "Body");                Xs.text (Sms.getbody ()); Xs.endtag (NULL, "Body"); Xs.starttag (NULL, "Date");                Xs.text (Sms.getdate ()); Xs.endtag (NULL, "Date"); Xs.starttag (NULL, "Address");                Xs.text (Sms.getaddress ()); Xs.endtag (NULL, "Address"); Xs.starttag (NULL, "type");                Xs.text (Sms.gettype ()); Xs.endtag (NULL, "type"); Xs.endtag (NULL, "SMS"); } Xs.endtag (NULL, "message"); //indicates the end of document generationxs.enddocument (); } Catch(Exception e) {e.printstacktrace (); } finally {            if(Fos! =NULL) {fos.close (); LOG.I ("Back", "33333"); }} toast.maketext ( This, "Backup Complete", 0). Show (); }}

Generating an XML file from the XmlSerializer interface

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.