Parsing the serializable serialization _android in Android

Source: Internet
Author: User
Tags serialization

1. Why do you want to serialize?

--Keep Java objects in memory on disk for persistent storage

--Transfer objects over the network

--Transmitted via RMI (remote Procedure call invocation).

By serialization, the object can be transformed into a platform-independent binary stream, deserialized before reuse, and converted to a Java object.

(Remote procedure calls for distributed Java applications that shield developers from different JVMs and network connections, and that objects distributed across different JVMs seem to exist in a unified JVM for easy communication)

2. How do I get Java objects to be serialized?

In Java, the target class is required to implement the serializable interface without implementing any methods. The serializable interface is a markup interface used to indicate that a class can be serialized.

3. How to use serialization and deserialization?

Serialization: Using the WriteObject () method of the ObjectOutputStream object output stream, the object can be written to the output stream.

Deserialization: Writes the ReadObject () method of the inflow using the ObjectInputStream object and casts it to a known target class.

4. Serialization of object references

If a class person has a member variable that references another class (such as Class Personinfo). That

Class Person implements serializable{

   String name;

   Personinfo info;

}

If you want to serialize the person class, you must satisfy: The Personinfo class can also be serialized, that is, the serializable interface is also implemented.

Class Personinfo implements Serializable

5, multiple objects referencing the same child object

Personinfo info = new Personinfo ("Male", "a");

person Xiaomi = new Person ("xiaoming", info);

Person Dabai = new Person ("big white", info);

If the above three objects are serialized sequentially, the two objects below all point to the same object above, that is, there is an info object, Java, in order to prevent the serialization of each object when serializing three info objects, set if the same Java object is serialized multiple times, This object is only converted to a byte sequence output at the first serialization, and then serialized to the first serialized number, without serializing the object.

6. Serialization of the parent class

If the parent class implements the Serializable interface, the subclass is automatically serializable and does not need to be shown to implement the interface.

7. Use serializable to save custom data to local example
mainactivity is as follows:

Package cc.test.serializable;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.util.ArrayList;
Import android.app.Activity;
Import Android.os.Bundle;
Import android.os.Environment;
 /** * Demo Description: * arraylist< custom data > on SDcard access. * * Differences between parcelable and serializable: * Recommended use of parcelable for data transfer between the memory, such as the transfer between the activity * For example: http://blog.csdn.net/lfdfhl/article/
  details/10961459 * It is recommended to use serializable/public class testserializableactivity to save to local or network transfer extends activity {@Override
    public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
  Testserializable ();
    private void Testserializable () {FileOutputStream fileoutputstream=null;
    ObjectOutputStream ObjectOutputStream =null;
    FileInputStream fileinputstream = null;
  ObjectInputStream objectinputstream = null;  arraylist<student> studentsarraylist = new arraylist<student> ();
    Student Student = null;
      for (int i = 1; i < 5; i++) {student = new student (i, "xiaoming" + i);
    Studentsarraylist.add (student);
                 try {//Deposit data File File = new file (Environment.getexternalstoragedirectory (). ToString ()
      + File.separator + "Test" +file.separator + "Data.dat");
      if (!file.getparentfile (). exists ()) {File.getparentfile (). Mkdirs ();
      } if (!file.exists ()) {file.createnewfile ();
      } fileoutputstream= New FileOutputStream (file.tostring ());
      objectoutputstream= new ObjectOutputStream (FileOutputStream);
       Objectoutputstream.writeobject (studentsarraylist);
      Remove Data FileInputStream = new FileInputStream (file.tostring ());
      ObjectInputStream = new ObjectInputStream (FileInputStream);
  Arraylist<student> savedarraylist = (arraylist<student>) objectinputstream.readobject ();    for (int i = 0; i < savedarraylist.size (); i++) {System.out.println ("extracted data:" + savedarraylist.get (i). tostr
      ing ());
        } catch (Exception e) {//Todo:handle Exception}finally{if (objectoutputstream!=null) {
        try {objectoutputstream.close ();
        catch (IOException e) {e.printstacktrace ();
        } if (Fileoutputstream!=null) {try {fileoutputstream.close ();
        catch (IOException e) {e.printstacktrace ();
        } if (Objectinputstream!=null) {try {objectinputstream.close ();
        catch (IOException e) {e.printstacktrace ();
        } if (Fileinputstream!=null) {try {fileinputstream.close ();
        catch (IOException e) {e.printstacktrace ();
 }
      }
    }
  }
}

Student is as follows:

Package cc.test.serializable;
Import java.io.Serializable;
public class Student implements Serializable {
  private Integer ID;
  private String name;
  Note Define this field public
  static final long serialversionuid = 9527L;
  Public Student () {
    super ();
  }
  Public Student (Integer ID, String name) {
    super ();
    This.id = ID;
    this.name = name;
  Public Integer GetId () {return
    ID;
  }
  public void SetId (Integer id) {
    this.id = ID;
  }
  Public String GetName () {return
    name;
  }
  public void SetName (String name) {
    this.name = name;
  }
  @Override public
  String toString () {return
    "Student [id= + ID +", name= "+ name +"] ";
  }
}

Main.xml is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
  android:layout_width=" fill_parent "
  android:layout_height=" fill_parent "
  android:o" rientation= "vertical" >
  <textview
    android:layout_width= "Fill_parent"
    Wrap_content "
    android:text=" @string/hello "/>
</LinearLayout>

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.