The storage and reading summary of Android serialization and the simple use of _android

Source: Internet
Author: User
Tags gettext object serialization serialization

Android serialization

1. The purpose of serialization

(1). Permanently save object Data (Save object data in a file, or disk

(2). Object data is transmitted over the network through serialization (because network traffic transmits data in a byte stream). So the purpose of serialization is to convert the object data into the form of a byte stream.

(3). The object data is passed between processes (the object data is passed between the activity, and the object data needs to be serialized in the current action). Deserialization is required in another activity to speak of data removal

(4). The Java platform allows us to create reusable Java objects in memory. In general, however, these objects can exist only when the JVM is running, that is, the life cycle of these objects is not longer than the JVM's lifecycle (that is, each object is in the JVM), but in real-world applications, You may want to stop the JVM from running, but have to save some of the specified objects and re-read the saved objects in the future. This is the function that Java object serialization can achieve. (You can choose to save in the form of a database, or file)

(5). When serializing an object, it is only serialized for a variable and not serialized for a method.

(6). Between intent, the basic data types are directly related to the transfer, but once the data type is more complex, it needs to be serialized operation.

There are two ways to implement serialization in Android: Serializable interface and Parcelable interface, in this paper, the two methods are summarized and used briefly.

A Related concepts

(i) The reason for serialization (the effect that serialization can achieve)

1. Permanently save the object, save the object's byte sequence to the local file;

2. Objects are passed through the network; 3. Objects are passed between IPC.

(ii) Methods of serialization

In the Android system, there are generally two methods for serialization, namely, implementing the Serializable interface and the Parcelable interface, where the Serializable interface is a serialized interface from Java, The parcelable is a serialized interface with Android. Both of these serialization interfaces have their own advantages and disadvantages, and we need to use them for different situations.

1. Use the Parcelable interface when more memory is required.

Serializable produces a large number of temporary variables when serialized, causing frequent GC, compared to parcelable performance (after all, Android), so when using memory ( For example, serializing an object in a network to pass objects or serialize objects between processes, it is more recommended to use the Parcelable interface.

2. Use the serializable interface when local storage is required.

But Parcelable has an obvious drawback: it cannot be used in situations where you want to store data on disk (such as permanently saving objects, storing byte sequences of objects in a local file) because parcel is not a common serialization mechanism for better implementation of objects in the IPC. When changing the underlying implementation of any parcel data may result in previous data being unreadable, it is recommended that serializable be used at this time.

Two Use of the Serializable interface

The Serializable interface implementation is simple, and the system will automatically serialize it by simply inheriting the serializable of the class that needs to be serialized. The store uses FileOutputStream to construct a objectoutputstream that uses WriteObject to store objects. Use FileInputStream to construct a objectinputstream when reading, and use ReadObject to read objects.

(i) Design of layout document Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" a ndroid:layout_height= "match_parent" android:orientation= "vertical" > <edittext android:layout_width= "ma 
    Tch_parent "android:layout_height=" wrap_content "android:id=" @+id/main_et_name "android:hint=" "Your username"/> <edittext android:layout_width= "match_parent" android:layout_height= wrap_content "android:id=" @+id/m Ain_et_password "android:hint=" Your password/> <edittext android:layout_width= "Match_parent" Android: layout_height= "Wrap_content" android:id= "@+id/main_et_age" android:hint= "Your Age"/> <button Android : onclick= "Save" android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Saving Data"/ > <button android:onclick= "read" android:layout_width= "wrap_content" android:layout_height= "Wrap_con Tent "android:text=" readFetch data "/> <textview android:layout_width=" match_parent android:layout_height= "Wrap_content" Android: text= "Data" android:id= "@+id/main_tv"/> </LinearLayout>

Interface design: input data through several input boxes, two buttons one to save the data, one to read the data, and the data to read to display in a text box.

(ii) Create an attribute class inheritance serializable

Package com.example.lesson18_serializable;
Import java.io.Serializable;
/**
 * Attribute class, used to store data, inherit interface serializable, but do not rewrite any methods!
 *
/public class people implements serializable{
  //define basic information
  String name;
  String password;
  int age;
  Parameterless construction method Public
  people () {
    super ();
  }
  A parametric construction method that facilitates data writing to public
  people (string name, string password, int age) {
    super ();
    this.name = name;
    This.password = password;
    This.age = age;
  }

  Overrides the ToString method to easily display
  @Override public
  String toString () {return
    "people [name=" + name + ", password=" + PA ssWOrd + ", age="
        + age;
  }

}

(iii) Class of the Main method

Package com.example.lesson18_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 android.app.Activity;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.EditText;

Import Android.widget.TextView; public class Mainactivity extends the activity {//Save the Path String path=environment.getexternalstoragedirectory () of the file. Getabsol
  Utepath () + "/people.txt";
  Define controls within the layout EditText edit_name;
  EditText Edit_password;
  EditText Edit_age;


  TextView text;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Instantiate the layout control edit_name= (edittext) Findviewbyid (r.id.main_et_name);
    Edit_password= (EditText) Findviewbyid (R.id.main_et_password); Edit_age= (EditText) FindviewByid (R.id.main_et_age);
  text= (TextView) Findviewbyid (R.ID.MAIN_TV);
    //Save Data public void Save (view view) {ObjectOutputStream fos=null;
      try {//If the file does not exist, create the file, file=new file (path);
      File.createnewfile ();
      Get output stream//here if the file does not exist the file will be created, which is a different place to write the file and read the file Fos=new objectoutputstream (new FileOutputStream (file));
      Gets the file in the input box to write to String Name=edit_name.gettext (). toString ();
      String Password=edit_password.gettext (). toString ();
      int Age=integer.parseint (Edit_age.gettext (). toString ());
      People people=new people (name, password, age);
    There is no longer a normal write method//To use WriteObject fos.writeobject (people);;
    catch (Exception e) {e.printstacktrace ();
        }finally{try {if (fos!=null) {fos.close (); Read data public void read (view view) {ObjectInputStream ois=n by catch (IOException e) {}}}
    ull; try {log.e ("TAG", New File (path). GETabsolutepath () + "<---");
      Gets the input stream ois=new ObjectInputStream (new FileInputStream (path));
      Gets the data Object people=ois.readobject () in the file;
    Display the data in the TextView Text.settext (people.tostring ());
    catch (Exception e) {e.printstacktrace ();
        }finally{try {if (ois!=null) {ois.close ();
      } catch (IOException e) {e.printstacktrace (); }
    }
  }

}

This is used to store data in a way that is stored externally, and you need to add permissions:

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

The interface after the program is run:

Enter the corresponding information, click Save, and then click to read the displayed results:

Where the data is stored in the local file, the next time you do not write data, you can directly read the last written file.

Three Use of the Parcelable interface

Use the method process to trouble some!

The implementation of Parcelable interface can be divided into a few steps:

1. Let attribute class model implement Parcelable interface 2. Rewrite the Writetoparcel method to serialize your object into a parcel object,

That is, the data of the class is written to the externally provided parcel, the data to be passed to the parcel container is saved to obtain the data from the parcel container. The writing method for the file here is very important.

3. Rewrite the Describecontents method, the Content interface description, the default return 0 can be. This method is basically useless! 4. Instantiate the static internal object Creator implement the interface Parcelable.creator and override the Read abstract method.

The method of reading here is also important and must be consistent with the order in which they are written. The name of the creator interface object here is fixed, and if it is changed to the bottom of the other name it will not recognize the interface!

Note: If you think of parcel as a stream, you first write the object into the stream through the Writetoparcel, and then read the object from the stream by Createfromparcel, so the write order and read Order of the class implementation must be the same.

Here the design program jumps from one page to another and passes the object's data past.

(i) Design attribute class inherits Parcelable interface

Package com.example.lesson18_parcalable;
Import Android.os.Parcel;
Import android.os.Parcelable;

  /** * Attribute class, inherit parcelable * Implement two methods, implement object writing within one of the methods * Create an interface class creator, rewrite the method of reading the object * * public class User implements parcelable{
  The user's various data definitions String name;
  String password;
  int age;
  Double money;

  Boolean isadmin; Public user () {}//write a construction method to facilitate writing data public user (string name, string password, int age, double, Boolean isadm
    IN) {super ();
    THIS.name = name;
    This.password = password;
    This.age = age;
    This.money = money;
  This.isadmin = ISAdmin;
  @Override//This method has nothing to do with public int describecontents () {return 0;
     @Override//The underlying implementation of the write data is public void Writetoparcel (Parcel arg0, int arg1) {arg0.writestring (name);
     arg0.writestring (password);
     Arg0.writeint (age);
     Arg0.writedouble (Money);
  The Boolean type of data is processed, True1,false0 arg0.writeint (isadmin?1:0); }//Instantiate static internal object creator implement interface, creator name can not change, otherwise it will error public static CrEator creator=new creator<user> () {@Override//the underlying implementation of the reading data, to be consistent with the sequence of data to be written public User Createfromparcel p
      Arcel arg0) {User user=new user ();
      User.name=arg0.readstring ();
      User.password=arg0.readstring ();
      User.age=arg0.readint ();
      User.money=arg0.readdouble ();
      Boolean type of data to be processed user.isadmin=arg0.readint () ==1?true:false;
    return user;
    @Override public user[] NewArray (int arg0) {//back to new USER[ARG0];

  }
  }; From the ToString method @Override public String toString () {return "User [name=" + name +], password= "+ password +", age
  = "+ Age +", money= "+ Money +", isadmin= "+ ISAdmin +"]; }

}

(ii) The design of the class of the Main method

Package com.example.lesson18_parcalable;

Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;

public class Mainactivity extends activity {

  @Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate); 

    Button Button=new button (this);
    Button.settext ("Jump to B page");

    Setcontentview (button);
    Button.setonclicklistener (New Onclicklistener () {      
      @Override public
      void OnClick (View arg0) {
         // Jumps to another page, the object's data also passes past
        Intent intent=new Intent (mainactivity.this,otheractivity.class);
        Define data
        user User=new User ("Liwenzhi", "123456", 22,1000000,true);
        Put the data inside the intent object
        Intent.putextra ("user", user);
        Implementation page Jump
        startactivity (intent);}}

The above class is also very simple. Design a button listener to jump to another page.

(iii) Design of another page

Package com.example.lesson18_parcalable;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.widget.TextView;

public class Otheractivity extends activity{
  @Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    TextView textview=new TextView (this);
    Textview.settextsize (a);
    Gets the data passed over the
    user user=getintent (). Getparcelableextra ("user");
    Textview.settext (User.tostring ());   
    Setcontentview (TextView);



  }

The page above is also relatively simple, receiving objects passed over from the previous page and then appearing in a TextView.

The display interface after the program is run:

Click on the large button to display the interface:

The above data is written dead, but also can be used to the first program to use several input boxes to determine the data.

Compare the methods and effects of the two interfaces implementations:

For the first program using serializable to implement the data transfer, and the data is stored locally, even if the program is uninstalled, other programs as long as the file path is correct, you can access the saved file data, but also can be used to do interprocess communication, but this needs to consume some memory.

The second program uses parcalable to implement data transfer, where the data cannot be saved to the local, with less memory footprint and more suitable for data transfer between processes.
For application: Network information transmission and process data transfer using parcalable to achieve data transmission is a bit more.

The size of the information passed by these two types of data is generally not large data.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.