Serializing objects in Android to XML and XML and deserializing objects

Source: Internet
Author: User

Package Com.example.xmloperation;import Java.io.file;import java.io.fileoutputstream;import Java.util.arraylist;import Java.util.list;import Java.util.random;import Org.xmlpull.v1.xmlpullparser;import Org.xmlpull.v1.xmlpullparserexception;import Org.xmlpull.v1.xmlserializer;import Android.annotation.SuppressLint ; Import Android.os.bundle;import Android.os.environment;import Android.support.v7.app.actionbaractivity;import Android.util.log;import Android.util.xml;import Android.view.view;import Android.widget.textview;import Android.widget.toast;import Com.example.bean.SmsInfo; Public classMainactivity extends Actionbaractivity {PrivateTextView content; PrivateList<smsinfo> Smsinfos =NewArraylist<smsinfo>(); @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Content=(TextView) Findviewbyid (r.id.tv); //To sequence an object//1: We can use the simulation method, the use of StringBuilder to assemble the XML file, but the method is not flexible enough to deal with the trouble, but the implementation of the bottom of the tool is basically achieved.     }            //2: Use Android-provided xml.serializer to serialize object text XML@SuppressLint ("Showtoast")     Public voidserializer2xml (view view) {//Initialize SMSinit (); LOG.I ("mainactivity","Start Serialization"); XmlSerializer Serializer=Xml.newserializer (); File File=NewFile (Environment.getexternalstoragedirectory (),"Smsinfo.xml");        FileOutputStream OS; Try{OS=Newfileoutputstream (file); Serializer.setoutput (OS,"Utf-8"); Serializer.startdocument ("Utf-8",true); Serializer.starttag (NULL,"SMSS");  for(Smsinfo Info:smsinfos) {Serializer.starttag (NULL,"SMS"); Serializer.attribute (NULL,"ID", Info.getid () +""); Serializer.starttag (NULL,"Body");                Serializer.text (Info.getbody ()); Serializer.endtag (NULL,"Body"); Serializer.starttag (NULL,"type"); Serializer.text (Info.gettype ()+""); Serializer.endtag (NULL,"type"); Serializer.starttag (NULL,"Date"); Serializer.text (Info.getdate ()+""); Serializer.endtag (NULL,"Date"); Serializer.starttag (NULL,"Address");                Serializer.text (Info.getaddress ()); Serializer.endtag (NULL,"Address"); Serializer.endtag (NULL,"SMS"); } Serializer.endtag (NULL,"SMSS");                        Serializer.enddocument ();                        Os.close (); Toast.maketext ( This,"serialization succeeds",0). Show (); } Catch(Exception e) {e.printstacktrace (); Toast.maketext ( This,"Serialization Failed",0). Show (); }    }        //parsing XML with pull     Public voidDeserialize (view view) {LOG.I ("mainactivity","Start deserialization"); Xmlpullparser Parser=Xml.newpullparser (); List<SmsInfo> Minfos =NULL; Smsinfo Info=NULL; Try{parser.setinput (mainactivity).class. getClassLoader (). getResourceAsStream ("Smsinfo.xml"),"Utf-8"); intType =Parser.geteventtype ();  while(Type! =xmlpullparser.end_document) {System. out. println ("type ="+type); Switch(type) { CaseXmlpullparser.start_tag:if("SMSS". Equals (Parser.getname ())) {Minfos=NewArraylist<smsinfo>(); } Else if("SMS". Equals (Parser.getname ())) {Info=NewSmsinfo (); Info.setid (Integer.parseint (Parser.getattributevalue (0))); } Else if("Body". Equals (Parser.getname ()))                        {Info.setbody (Parser.nexttext ()); } Else if("type". Equals (Parser.getname ())) {String temp=Parser.nexttext (); //System.out.println ("temp =" + temp);Info.settype (Integer.parseint (temp)); } Else if("Date". Equals (Parser.getname ()))                        {Info.setdate (Long.parselong (Parser.nexttext ())); } Else if("Address". Equals (Parser.getname ()))                        {info.setaddress (Parser.nexttext ()); }                         Break;  CaseXmlpullparser.end_tag:if("SMS". Equals (Parser.getname ()))                            {Minfos.add (info); Info=NULL; }                         Break; } type=Parser.next (); }        } Catch(Exception e) {e.printstacktrace (); Toast.maketext ( This,"deserialization failed",0). Show ();; } StringBuilder SB=NewStringBuilder (); System. out. println (Minfos.size ());  for(Smsinfo info1:minfos) {//System.out.println ("info =" + info.getaddress ());Sb.append (info1.tostring () +"\ n");                    } content.settext (Sb.tostring ()); }    Private voidinit () {random random=NewRandom (); LongAddress =18766960000l;  for(inti =0; I <Ten; ++i) {System. out. println ("i ="+i); Smsinfo Smsinfo=NewSmsinfo (System.currenttimemillis (), Random.nextint (2) +1,"SMS Content"+ I,""+address +I, i);        Smsinfos.add (Smsinfo); }    }}

In the middle of the pit dad is in the deserialization when you do not appear between each element of the XML space, empty text, or the pointer to the next point is empty text, parsing error occurs.

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.