In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Object serialization storage Serializable and Parceable how to analyze, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
When doing Android development, we sometimes need to use persistent storage of data, or transfer data between processes. The serialization of the object may be needed, and the serialized object can then be transmitted through Intent or Boundle. Next, I'd like to make some introductions.
1. What is serialization? what is deserialization?
Serialization: the process of converting data structures or objects into binary strings. Deserialization: the process of converting a binary string generated during serialization into a data structure or object.
To put it simply, serialization is storing the objects we generate (such as on disk) for future use or transmission over the network, while deserialization is the process of regenerating objects from the binary strings generated by our previous serialization. Note that here we repeatedly say serialization, deserialization, all for the object, not the class. Because we access and transfer objects, not classes, when we need to retrieve the previous object, it is read directly (from the file or network), rather than an object according to the class new, which needs to be noted.
two。 How to serialize
There are two ways of sequential conversation, one is to implement the Serializable interface, and the other is to implement the Parceable interface, which are described in detail below.
a. Implement the Serializable interface
This kind of serialization is provided by Java, its advantage is simple, in fact, the Serializable interface is an empty interface, so we do not need to implement any abstract methods, but we often need to declare a static variable identity (serialVersionUID) in the class, but this is not necessary, we do not declare, we can still implement serialization, but this will have a certain impact on deserialization It may cause the deserialization of the object to fail after we make changes to the class. The statement is as follows:
Private static final long serialVersionUID = 8711368828010083044L
Note that the value here can be any value.
Let's implement it in detail.
Package com.qc.admin.myserializableparceabledemo; import java.io.Serializable; / * Created by admin on 2016-12-1. * / public class User implements Serializable {private static final long serialVersionUID = 519067123721295773L; public int userId; public String userName; public boolean isMale; public User (int userId, String userName, boolean isMale) {this.userId = userId; this.userName = userName; this.isMale = isMale @ Override public String toString () {return "User {" + "userId =" + userId + ", userName =" + userName + ", isMale =" + isMale + "}";}}
Here is the serialization and deserialization process:
Private void beginSerizable () throws IOException, ClassNotFoundException {/ / Serialization User user = new User (2016, "qian", true); ObjectOutputStream out = new ObjectOutputStream (new File (getFilesDir (), "myfile.txt")); out.writeObject (user); out.close () / / deserialize / / Note that the following "/ myfile.txt" here is preceded by a slash "/", otherwise it will report the "FileNotFoundException" exception ObjectInputStream in = new ObjectInputStream (new FileInputStream (getFilesDir () + "/ myfile.txt")); User mUser = (User) in.readObject (); textView.setText (mUser.toString ()); in.close () Log.i ("test", mUser.toString ();}
Screenshot of the running result:
Note: if you are calling the above methods in an Android project, don't forget to configure the following permissions in the Manifest.xml file:
b. Implement the Parceable interface
This approach is provided by Android, which is a little more complicated than the previous one. We need to enjoy serialization and deserialization by ourselves, but it is more efficient and does not require a large number of IAndroid O operations. And this is also the serialization method recommended by Android, so we should * * Parceable. Once this interface is implemented, the objects of a class can be serialized and passed through Intent and Binder. Take a look at the following example:
Public class Book implements Parcelable {public String bookTitle; public int bookId; protected Book (Parcel in) {bookTitle = in.readString (); bookId = in.readInt ();} public static final Creator CREATOR = new Creator () {@ Override public Book createFromParcel (Parcel in) {return new Book (in) @ Override public Book [] newArray (int size) {return new Book [size];}}; @ Override public int describeContents () {return 0;} @ Override public void writeToParcel (Parcel parcel, int I) {parcel.writeString (bookTitle); parcel.writeInt (bookId);}}
Here, the Book class implements the Parcelable interface. In fact, in Android Studio IDE, the above process is very simple. We just need to define a class, implement the Parcelable interface, and then define our properties or fields in it. According to the prompted error, we overwrite the corresponding method according to the prompted method, and then everything can be generated automatically (but if you need to construct the method, then you need to generate it automatically. The toString () method is also implemented by yourself, so don't worry about the hassle of implementing the Parceable interface in Android development, because AS is automatically generated for you. Now that we have fully implemented the Parceable interface for the Book class, how do we serialize and deserialize it next? If you say, as you just said, it will soon be OK to use the way of reading files. When you do that, you will find that you will report the following error:
Why???... What happened? Remind us that the Book class does not implement serialization:
/ System.err: java.io.NotSerializableException: com.qc.admin.myserializableparceabledemo.Book
Well, the reason for this problem is not that there is something wrong with our implementation process, but that the way we use this class does not work. At this point, we understand that there are differences between Serializable and Parceable in serialization. As we said just now, Parceable is more efficient and does not have a large number of Serializable O operations like Serializable. The specific meaning of this sentence shows the difference between Serializable and Parcelable: although both are used to support serialization and deserialization, the difference between the two lies in the storage media. Serializable is the serialization of the object stored on the hard disk, using the way of reading and writing, while Parcelable is stored in memory, is for memory read and write, familiar with the computer composition principle of friends all know, memory read and write speed is obviously much greater than the read and write speed of Android, which is why Android recommends using Parcelable this way to achieve object serialization.
So how should we use objects serialized by implementing the Parcelable interface? The answer is: through Intent, except for basic types, Intent can only transfer serialized objects. There are also two corresponding methods for these two serialization methods:
MIntent.getSerializableExtra (string name); mIntent.getParcelableExtra (String name)
Of course, there is no such distinction between the operations that are put in, they are all methods:
MIntent.putExtra ()
We can put the serialized object into the Intent in * Activity and take it out in another Activity, for example, get the object on the other end, for example:
Bundle mBundle = getIntent () .getExtras (); Book mBook = mBundle.getParcelable ("book1")
Let's take a look at the process of class User implementing the Parceable interface, which contains a serializable class Book. The details are a little different from the above:
Package com.qc.admin.myserializableparceabledemo; import android.os.Parcel; import android.os.Parcelable; / * Created by admin on 2016-12-1. * / public class User implements Parcelable {public int userId; public String userName; public boolean isMale; public Book book; public User (int userId, String userName, boolean isMale, Book book) {this.userId = userId; this.userName = userName; this.isMale = isMale This.book = book;} protected User (Parcel in) {userId = in.readInt (); userName = in.readString (); isMale = in.readByte ()! = 0; / / this is the difference 1 / / can also be done in this way: book = in.readParcelable (Thread.currentThread (). GetContextClassLoader ()) Book = in.readParcelable (Book.class.getClassLoader ());} public static final Creator CREATOR = new Creator () {@ Override public User createFromParcel (Parcel in) {return new User (in);} @ Override public User [] newArray (int size) {return new User [size];}} / / it should return 0 in almost all cases, and only if there is a file description in the current object, this method returns CONTENTS_FILE_DESCRIPTOR (constant value 1) @ Override public int describeContents () {return 0 } / / write the object into the serialization structure, where I identity has two values. 0 or 1 (PARCELABLE_WRITE_RETURN_VALUE) / / 1 means that the current object needs to be returned as a return value and resources cannot be released immediately. In almost all cases, 0 @ Override public void writeToParcel (Parcel parcel, int I) {parcel.writeInt (userId); parcel.writeString (userName) / / Note here, instead of writing the Boolean value directly, write the integer value parcel.writeByte ((byte) (isMale? 1: 0)); / / this is the difference 2 parcel.writeParcelable (book, I) @ Override public String toString () {return "User {" + "userId =" + userId + ", userName =" + userName + ", isMale =" + isMale + "book =" + book.toString () + "}";}}
As you can see, the results have been printed correctly:
Note: in Parcelable, we cannot directly write the boolean value, but convert it to an integer value to save, here is Byte, of course, you can also use Int and so on.
After reading the above, have you mastered how to analyze the serialization store Serializable and Parceable of the object? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.