Android 序列化
1.序列化的目的
(1).永久的儲存對象資料(將對象資料儲存在檔案當中,或者是磁碟中
(2).通過序列化操作將對象資料在網路上進行傳輸(由於網路傳輸是以位元組流的方式對資料進行傳輸的.因此序列化的目的是將對象資料轉換成位元組流的形式)
(3).將對象資料在進程之間進行傳遞(Activity之間傳遞對象資料時,需要在當前的Activity中對對象資料進行序列化操作.在另一個Activity中需要進行還原序列化操作講資料取出)
(4).Java平台允許我們在記憶體中建立可複用的Java對象,但一般情況下,只有當JVM處於運行時,這些對象才可能存在,即,這些對象的生命週期不會比JVM的生命週期更長(即每個對象都在JVM中)但在現實應用中,就可能要停止JVM運行,但有要儲存某些指定的對象,並在將來重新讀取被儲存的對象。這是Java對象序列化就能夠實現該功能。(可選擇入資料庫、或檔案的形式儲存)
(5).序列化對象的時候只是針對變數進行序列化,不針對方法進行序列化.
(6).在Intent之間,基本的資料類型直接進行相關傳遞即可,但是一旦資料類型比較複雜的時候,就需要進行序列化操作了.
Android中序列化的實現有兩種方式:Serializable介面和Parcelable介面,本文對這兩種方式進行簡單的總結和使用。
一.相關概念
(一)序列化的原因(序列化能實現的效果)
1.永久性儲存對象,儲存對象的位元組序列到本地檔案中;
2.對象在網路中傳遞;3.對象在IPC間傳遞。
(二)序列化的方法
在Android系統中關於序列化的方法一般有兩種,分別是實現Serializable介面和Parcelable介面,其中Serializable介面是來自Java中的序列化介面,而Parcelable是Android內建的序列化 介面。 上述的兩種序列化介面都有各自不同的優缺點,我們在實際使用時需根據不同情況而定。
1.當需要記憶體較多時使用Parcelable介面。
Serializable在序列化的時候會產生大量的臨時變數,從而引起頻繁的GC,而相比之下 Parcelable的效能更高(畢竟是Android內建的),所以當在使用記憶體時(如:序列化對象在網路中傳遞對象或序列化在進程間傳遞對象),更推薦使用Parcelable介面。
2.當需要本機存放區時,使用Serializable 介面。
但Parcelable有個明顯的缺點:不能能使用在要將資料存放區在磁碟上的情況(如:永久性保 存對象,儲存對象的位元組序列到本地檔案中),因為Parcel本質上為了更好的實現對象在 IPC間傳遞,並不是一個通用的序列化機制,當改變任何Parcel中資料的底層實現都可能導致之前的資料不可讀取,所以此時還是建議使用Serializable 。
二.Serializable介面的使用
Serializable的介面實現很簡單,只需讓需要序列化的類繼承Serializable即可,系統會自動將其序列化。儲存時使用FileOutputStream構造一個ObjectOutputStream,使用writeObject 儲存物件。讀取時使用FileInputStream構造一個ObjectInputStream,使用readObject讀取對象。
(一)布局檔案activity_main.xml的設計
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/main_et_name" android:hint="你的使用者名稱" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/main_et_password" android:hint="你的密碼" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/main_et_age" android:hint="你的年齡" /> <Button android:onClick="save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="儲存資料" /> <Button android:onClick="read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="讀取資料" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="資料" android:id="@+id/main_tv" /></LinearLayout>
介面設計:通過幾個輸入框輸入資料,兩個按鈕一個儲存資料一個讀取資料,讀取的資料顯示在一個文字框下。
(二)建立一個屬性類繼承Serializable
package com.example.lesson18_serializable;import java.io.Serializable;/** *屬性類,用來儲存資料,繼承介面Serializable,但是什麼方法都不用重寫! */public class People implements Serializable{ //定義基本資料 String name; String password; int age; //無參構造方法 public People() { super(); } //有參構造方法,方便資料寫入 public People(String name, String password, int age) { super(); this.name = name; this.password = password; this.age = age; } //重寫toString方法,方便顯示 @Override public String toString() { return "People [name=" + name + ", password=" + password + ", age=" + age ; }}
(三)主方法的類
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 Activity { //儲存檔案的路徑 String path=Environment.getExternalStorageDirectory().getAbsolutePath()+"/people.txt"; //定義布局內的控制項 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); //執行個體化布局控制項 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); } //儲存資料 public void save(View view){ ObjectOutputStream fos=null; try { //如果檔案不存在就建立檔案 File file=new File(path); //file.createNewFile(); //擷取輸出資料流 //這裡如果檔案不存在會建立檔案,這是寫檔案和讀檔案不同的地方 fos=new ObjectOutputStream(new FileOutputStream(file)); //擷取輸入框內的檔案進行寫入 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); //這裡不能再用普通的write的方法了 //要使用writeObject fos.writeObject(people);; } catch (Exception e) { e.printStackTrace(); }finally{ try { if (fos!=null) { fos.close(); } } catch (IOException e) { } } } //讀取資料 public void read(View view){ ObjectInputStream ois=null; try { Log.e("TAG", new File(path).getAbsolutePath()+"<---"); //擷取輸入資料流 ois=new ObjectInputStream(new FileInputStream(new File(path))); //擷取檔案中的資料 Object people=ois.readObject(); //把資料顯示在TextView中 text.setText(people.toString()); } catch (Exception e) { e.printStackTrace(); }finally{ try { if (ois!=null) { ois.close(); } } catch (IOException e) { e.printStackTrace(); } } }}
這裡使用但是外部儲存的方式來儲存資料,需要添加許可權:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
程式運行後的介面:
輸入對應的資訊,點擊儲存,再點擊讀取顯示的結果:
其中這裡的資料是儲存再本地檔案中的,下次不用寫入資料,可以直接讀取上次寫入的檔案。
三.Parcelable介面的使用
使用的方法過程要麻煩一些!
實現Parcelable介面主要可以分為一下幾步:
1.讓屬性類Model實現Parcelable介面2.重寫writeToParcel方法,將你的對象序列化為一個Parcel對象,
即:將類的資料寫入外部提供的Parcel中,打包需要傳遞的資料到Parcel容器儲存,以便從Parcel容器擷取資料。 這裡的檔案的寫入方法非常重要。
3.重寫describeContents方法,內容介面描述,預設返回0即可。 這個方法基本沒有用!4.執行個體化靜態內部對象CREATOR實現介面Parcelable.Creator,並重寫讀取的抽象方法。
這裡的讀取的方法也是很重要的,必須和寫的時候的順序是一致的。這裡的CREATOR介面對象的名字是固定的,如果改成其他名字底層會識別不到這個介面!
注意:若將Parcel看成是一個流,則先通過writeToParcel把對象寫到流裡面,再通過 createFromParcel從流裡讀取對象,因此類實現的寫入順序和讀出順序必須一致。
這裡設計程式從一個頁面跳轉到另一個頁面,並把對象的資料傳遞過去。
(一)設計屬性類繼承Parcelable介面
package com.example.lesson18_parcalable;import android.os.Parcel;import android.os.Parcelable;/** *屬性類,繼承Parcelable *實現兩個方法,在其中一個方法內實現對象寫入的操作 *建立一個介面類CREATOR,重寫讀取對象的方法 */public class User implements Parcelable{ //User的各種資料的定義 String name; String password; int age; double money; boolean isAdmin; public User(){} //寫一個構造方法來方便寫入資料 public User(String name, String password, int age, double money, boolean isAdmin) { super(); this.name = name; this.password = password; this.age = age; this.money = money; this.isAdmin = isAdmin; } @Override // 這個方法沒什麼用 public int describeContents() { return 0; } @Override // 寫資料的底層實現 public void writeToParcel(Parcel arg0, int arg1) { arg0.writeString(name); arg0.writeString(password); arg0.writeInt(age); arg0.writeDouble(money); //把布爾類型的資料做處理,true1,false0 arg0.writeInt(isAdmin?1:0); } //執行個體化靜態內部對象CREATOR實現介面,CREATOR名字不能改變,否則會報錯 public static Creator CREATOR=new Creator<User>() { @Override // 讀書資料的底層實現,要和寫入的資料的順序保持一致 public User createFromParcel(Parcel arg0) { User user=new User(); user.name=arg0.readString(); user.password=arg0.readString(); user.age=arg0.readInt(); user.money=arg0.readDouble(); //布爾類型的資料要處理 user.isAdmin=arg0.readInt()==1?true:false; return user; } @Override public User[] newArray(int arg0) { //返回 return new User[arg0]; } }; //從toString方法 @Override public String toString() { return "User [name=" + name + ", password=" + password + ", age=" + age + ", money=" + money + ", isAdmin=" + isAdmin + "]"; }}
(二)主方法的類的設計
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("跳轉到B頁面"); setContentView(button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //跳轉到另一個頁面,對象的資料也要傳遞過去 Intent intent=new Intent(MainActivity.this,OtherActivity.class); //定義資料 User user=new User("liwenzhi","123456",22,1000000,true); //把資料放到Intent對象裡面 intent.putExtra("user", user); //實現頁面跳轉 startActivity(intent); } }); }}
上面這個類也是很簡單的。設計一個按鈕監聽跳轉到另一個頁面。
(三)另一個頁面的設計
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(30); //擷取傳遞過來的資料 User user=getIntent().getParcelableExtra("user"); textView.setText(user.toString()); setContentView(textView); }}
上面的頁面也是比較簡單的,接收從上一個頁面傳遞過來的對象,然後顯示在一個TextView。
程式運行後的顯示介面:
點擊大按鈕後,顯示的介面:
上面的資料的寫死的,其實也是可以向第一個程式那樣使用幾個輸入框來確定資料的。
對比這兩個介面實現的方法和效果:
對於第一個程式使用Serializable實現了資料的傳遞,並且資料是儲存在本地的,即使是程式被卸載了,其他程式只要是檔案路徑正確,也可以訪問儲存的檔案的資料,也是可以用來做進程間的通訊的,但是這樣需要消耗一些記憶體。
對比第二個程式使用Parcalable實現了資料的傳遞,這裡的資料是不能儲存到本地的,佔用的記憶體較少,比較適合用於進程間的資料傳遞。
對於應用方面:網路資訊傳遞和進程間資料傳遞使用Parcalable實現了資料的傳遞的方式是比較多一點的。
對於這兩種資料傳遞的資訊大小一般不能是很大的資料。
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!