Several types of Android data serialization schemes

Source: Internet
Author: User
Tags object serialization

First, Introduction

The serialization of data plays an important role in Android development, whether it is in interprocess communication, local data storage, or network data transmission without the support of serialization. Choosing the right serialization scheme for different scenarios has a great impact on the performance of the application.

In a broad sense, data serialization is the process of converting a data structure or object into a format that we can store or transmit, in the process of serialization, the data structure or object writes its state information to a temporary or persistent store, and in the corresponding deserialization process, Can be said to be the process of restoring the generated data to a data structure or object.

In this way, data serialization is equivalent to extending our original object serialization concept, in object serialization and deserialization, we know two ways, one is the serializable interface provided in the Java language, and the other is the Parcelable interface provided by Android. And here, because we have extended this concept, we also need to consider several methods that are specifically serialized for the data structure, such as the data that the open API typically returns in JSON format, or our Android native SQLite database for local storage of data. Broadly speaking, these can be counted as the serialization of data.

Second, serializable interface

As mentioned earlier, the serializable interface is the Java language feature, is the simplest is one of the most widely used serialization scheme, it is important to note that the serializable interface is an identity interface, without implementing the method, Java will be the object of the serialization operation.

The object that implements the serializable interface here can be serialized, converting the Java object into a sequence of bytes, and the corresponding deserialization is the process of reverting the sequence of bytes to a Java object.

In a class that needs to be serialized, Serialversionuid is used to identify the serialized object, which is normally deserialized only if the Serialversionuid in the serialized data is the same as the serialversionuid of the current class.

ImportJava.io.*; Public classUserImplementsserializable{Private Static Final LongSerialversionuid= 123456;  Public intuserId;  PublicString UserName;  Public BooleanIsmale;  PublicUser (intUserid,string UserName,BooleanIsmale) {         This. userid=userId;  This. username=UserName;  This. Ismale =Ismale; }     Public BooleanToserial (user user)throwsioexception{ObjectOutputStream out=NULL; Booleanstatus=false; Try{ out=NewObjectOutputStream (NewFileOutputStream ("Cache.txt"));            Out.writeobject (user); Status=true; }Catch(FileNotFoundException e) {System.out.println ("NO FILE"); }finally{                if(out!=NULL) Out.close (); }        returnstatus; }     PublicUser toobject (String filename)throwsioexception{ObjectInputStream in=NULL; Booleanstatus=false; User User=NULL; Try{ in=NewObjectInputStream (Newfileinputstream (filename)); User=(User) in.readobject (); }Catch(ClassNotFoundException e) {System.out.println ("No file"); }finally{            if(in!=NULL) In.close (); }        returnuser; }     Public Static voidMain (string[] args)throwsioexception{User User=NewUser (0, "Jake",true);        System.out.println (user.toserial (user)); System.out.println (User.toobject ("Cache.txt"). GetClass ()); }}

Also, it is important to note that static member variables belong to a class and not to an object, so it is clear that it will not participate in the serialization process of the object. Second, the member variables marked with the transient keyword are not involved in the serialization process. Finally, this serialization method is based on disk or network.

Third, parcelable interface

The Parcelable interface is an interface provided by the Android API and, to a certain extent, it is more suitable for Android platforms. Unlike serializable, which is memory-based, the Parcelable interface is widely used for cross-process object delivery because memory reads and writes faster than the disk.

The following is a simple parcelable interface that is labeled as a serialization process:

ImportAndroid.os.Parcel;Importandroid.os.Parcelable; Public classUserImplementsparcelable { Public intuserId;  PublicString UserName;  Public BooleanIsmale;  PublicUser (intUserid,string UserName,BooleanIsmale) {         This. userid=userId;  This. username=UserName;  This. ismale=Ismale; }         Public Static FinalCreator<user> Creator =NewCreator<user>() {@Override PublicUser Createfromparcel (Parcel in) {return NewUser (in); } @Override PublicUser[] NewArray (intsize) {            return NewUser[size];    }    };  PublicUser (Parcel in) {userId=In.readint (); UserName=in.readstring (); Ismale=in.readint () ==1; } @Override Public intdescribecontents () {return0; } @Override Public voidWritetoparcel (Parcel out,intflags)        {Out.writeint (userId);        Out.writestring (UserName); Out.writeint (Ismale? 1:0); }}

As can be seen from the above, to implement a parcelable interface, you need to implement the following methods:

1. Constructor: Create the original object from the serialized object

2.describeContents: Description of the interface content, generally return 0 by default

3.writeToParcel: Serialized method that writes the data of the class to the parcel container

4. Static parcelable. Creator interface, this interface consists of two methods

1) Createformparcel: Deserialization method to revert parcel to Java object

2) NewArray: Provided to the outer class to deserialize this array to use.

Comparison of two methods of object serialization

Serializable is a serialized interface in Java, which is simple but expensive to use (because Serializable uses a reflection mechanism during serialization, resulting in a large number of temporary variables, resulting in frequent GC), and in the process of reading and writing data, It writes data to the hard disk or to the network via an IO stream.

While Parcelable is based on IBinder as the information carrier, the overhead in memory is relatively small, so when data transfer between memory, it is recommended to use parcelable, and parcelable to persist the data or network transmission operation Complex, It is generally recommended to use serializable at this time.

In addition serializable in the use of relatively simple, and parcelable in the use of manual to implement the interface method, in order to avoid the use of parcelable interface trouble, we introduce a plug-in, to automatically generate the corresponding code.

Five, parcelable plug-in

To avoid writing a lot of template code, here is a plugin in Android Strudio, Android parcelable code generator. Download and follow the plugin in Pulgins, then when we need to use the Parcelable interface, the plugin will automatically help us to convert the class object into the form of implementing the Parcelable interface.

Examples are as follows,

/***/Publicclass  bookitem    {public  String mname ;      Public Long mlasttime;      Public String mtitle;      Public String MPath;}

Then, like with the build getter and setter code, we can automatically generate the Parcelable form of code directly, and the results are as follows:

ImportAndroid.os.Parcel;Importandroid.os.Parcelable;/*** Created by DB on 2017/6/24.*/ Public classBookitemImplementsparcelable { PublicString Mname;  Public LongMlasttime;  PublicString Mtitle;  PublicString MPath; @Override Public intdescribecontents () {return0; } @Override Public voidWritetoparcel (Parcel dest,intflags) {dest.writestring ( This. Mname); Dest.writelong ( This. Mlasttime); Dest.writestring ( This. Mtitle); Dest.writestring ( This. MPath); }     PublicBookitem () {}protectedBookitem (Parcel in) { This. Mname =in.readstring ();  This. Mlasttime =In.readlong ();  This. Mtitle =in.readstring ();  This. MPath =in.readstring (); }     Public Static FinalParcelable.creator<bookitem> Creator =NewParcelable.creator<bookitem>() {@Override PublicBookitem Createfromparcel (Parcel source) {return NewBookitem (source); } @Override PublicBookitem[] NewArray (intsize) {            return NewBookitem[size]; }    };}

With this plugin, using the Parcelable interface is obviously a lot of convenience (can steal a lot of lazy)

VI. Serialization of data solutions

The following is a generalized serialization scheme, which differs from the previous two narrow or object serialization schemes, and the next several scenarios are for serialization scenarios in data transfer and stored procedures

1.SQLite

SQLite is primarily used to store complex relational data, and Android supports native support for SQLite database-related operations (Sqliteopenhelper), but because the native API interface is not friendly, it produces many ORM frameworks that encapsulate SQLite.

2.SharedPreferences

Sharedpreferences is a lightweight storage API available on the Android platform, typically used to store commonly used configuration information, which is essentially a key-value pair store that supports commonly used data types such as Boolean, float, int, Long and string storage and reading.

Read and store operations using Sharedpreferences are as follows:

Read:

1) Get Sharedpreferences object

Sharedpreferences mpreferences = context.getcsharedpreferences (preferences_name,context.mode_private);

2. Reading data stored in Sharedpreferences through the Sharedpreferences object

Mpreferences.getboolean (Key,defvalue);

Store:

1) Get Sharedpreferences.editor object

Sharedpreferences.editor Editor = Mpreferences.edit ();

2) write data to Sharedpreferences by Sharedpreferences.editor object.

Meditor.putboolean (KEY,B);

3) Call the Commit function to commit the data being written, thus completing the data store operation.

Meditor.commit ();

3.JSON

JSON is a lightweight form of data interaction, because its relative to the XML, smaller size, the network on the transmission of more browsing, is widely used on the mobile side. Most apps communicate with the server by using the JSON format.

Several types of Android data serialization schemes

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.