Sharedpreferences and serialization combine to save object data in Android

Source: Internet
Author: User
Tags sqlite database

Preface :

Recently in the user registration, encountered the need to fill out a lot of form data, it is not possible to complete all the data on a page, so the use of paging, because after users fill in the data data we need to fill in the data for a temporary record, when the user will be able to view and modify the page. At first, we will solve this problem from the angle of the data size, so there are several ways:

A, use temporary static variable static to save in memory

B, using Sharedpreferences to save

C. Using SQLite database

First to analyze the advantages and disadvantages of this 3 ways, A, advantages: with the arbitrary shortcomings: when the user's phone has a lot of data, easy to cause static loss.

B, as is known to all, Sharedpreferences is a lightweight storage class on the Android platform that provides the Android platform's regular long
Shaping, int shaping, string-type saving methods. For me, with so many forms of data, I didn't want a set in (I was too lazy), so I put him aside.

C, the use of SQLite database, this is a bit to take a cannon to hit the birds, overqualified, so decisively give up.

Now cut to the chase. Because the data in the form is generally an entity class that can be serialized, the purpose of the serialization itself is to convert the state information of the object into a form that can be stored or transmitted. During serialization, an object writes its current state to a temporary or persistent store. Later, the object can be recreated by reading or deserializing the state of the object from the store. In the end, it translates into binary data,

Now it leads me to the idea,

1. Class Objects 2. Serialization 3. Get String Data 4. Storage (Five ways to store Android) 5. Follow the storage method to get the data 6. Deserialization 7. Get the appropriate object

Paste the following code:

Person.java

Package Com.example.shareddatatest;import java.io.Serializable; Public classPerson implements Serializable {/**     *      */    Private StaticFinalLongSerialversionuid =1L;    String name; intAge ;    String address;    String education;    String Tel;  Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; }     PublicString geteducation () {returneducation; }     Public voidseteducation (String education) { This. Education =education; }     PublicString Gettel () {returnTel; }     Public voidSettel (String tel) { This. Tel =Tel; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex;    } String sex; @Override PublicString toString () {return "Person [Name="+ name +", age="+ Age +", address="+Address+", education="+ Education +", tel="+ Tel +", sex="+Sex+"]"; }}

Mainactivity.java

Package Com.example.shareddatatest;import Java.io.bytearrayinputstream;import java.io.ByteArrayOutputStream; Import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.util.hashmap;import Java.util.list;import Android.app.activity;import android.content.SharedPreferences; Import Android.content.sharedpreferences.editor;import Android.os.bundle;import Android.util.log;import Android.view.menu;import Android.view.View; Public classMainactivity extends Activity { person person=NULL; LongStartTime =0l; LongEndTime =0l; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main); person=NewPerson (); Person.setname ("LULU"); Person.setsex ("Bitch"); Person.setaddress ("Beijing Haidian"); Person.setage ( -); Person.settel ("1231312"); Person.seteducation ("Primary School"); }    /** * Serialized Object * * @param person * @return * @throws IOException*/    PrivateString serialize (person person) throws IOException {StartTime=System.currenttimemillis (); Bytearrayoutputstream Bytearrayoutputstream=NewBytearrayoutputstream (); ObjectOutputStream ObjectOutputStream=NewObjectOutputStream (Bytearrayoutputstream);        Objectoutputstream.writeobject (person); String Serstr= Bytearrayoutputstream.tostring ("iso-8859-1"); Serstr= Java.net.URLEncoder.encode (Serstr,"UTF-8");        Objectoutputstream.close ();        Bytearrayoutputstream.close (); LOG.D ("Serial","Serialize str ="+serstr); EndTime=System.currenttimemillis (); LOG.D ("Serial","the serialization time is:"+ (EndTime-startTime)); returnSerstr; }    /** * Deserialization Object * * @param str * @return * @throws IOException * @throws classnotfoundexception */    PrivatePerson deserialization (String str) throws IOException, ClassNotFoundException {startTime=System.currenttimemillis (); String Redstr= Java.net.URLDecoder.decode (str,"UTF-8"); Bytearrayinputstream Bytearrayinputstream=NewBytearrayinputstream (Redstr.getbytes ("iso-8859-1")); ObjectInputStream ObjectInputStream=NewObjectInputStream (Bytearrayinputstream); Person Person=(person) objectinputstream.readobject ();        Objectinputstream.close ();        Bytearrayinputstream.close (); EndTime=System.currenttimemillis (); LOG.D ("Serial","deserialization time is:"+ (EndTime-startTime)); returnPerson ; }    voidSaveobject (String strobject) {sharedpreferences SP= Getsharedpreferences (" Person",0); Editor Edit=Sp.edit (); Edit.putstring (" Person", Strobject);    Edit.commit (); } String GetObject () {sharedpreferences SP= Getsharedpreferences (" Person",0); returnSp.getstring (" Person",NULL); }     Public voidonclick (View v) {Switch(V.getid ()) { CaseR.id.button1:Try{saveobject (serialize (person)); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }             Break;  CaseR.id.button2:Try{ person person=deserialization (GetObject ()); LOG.D ("Serial", person.tostring ()); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }             Break; default:             Break; }    }}

The results of the Logcat are:

Sharedpreferences and serialization combine to save object data in Android

Related Article

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.