Android 序列化之parcelable的簡單使用

01 概念和使用場景

Android中序列化的兩個接口

Serializable
Parcelable

其中Serializable是Java自帶的序列化接口,Parcelable是Android特有的序列化接口

序列化的目的是:

  1. 對象數據的永久保存
  2. 通過網絡進行傳輸(網絡傳輸的是字節流,需要通過序列化將數據轉換成字節流)
  3. 對象數據的進程間的傳遞
  4. 使用Intent傳遞複雜的數據結構。

 

02 基本使用方法

使用舉例: Activity A 通過 Intent向Activity B傳遞Java複雜對象

A 中的代碼:其中userInfoRepBean已經實現了Parcelable接口

Intent intent = new Intent(this, ActivityTarget.class);
Bundle bundle = new Bundle();
//Parcelable 序列化
bundle.putParcelable(Constants.USER_INFO, userInfoRepBean);
intent.putExtras(bundle);
startActivity(intent);

B中的代碼:

Bundle extras = intent.getExtras();
//Parcelable 反序列化
UserInfoRepBean person = extras.getParcelable(Constants.USER_INFO);
Log.d(TAG, "initData: nickname is " + person.getResult().getNickName());

 

03 Android studio中的插件

使用Android Parcelable code generator 插件可以快速的是你的JavaBean 實現Parcelable接口。

Parcelable插件名稱

 

找到需要實現Parcelable接口的類,右擊,generate,然後選擇Parcelable

使用Parcelable插件

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章