Intent或持久化存儲處理復(fù)雜對象

歡迎Follow我的GitHub, 關(guān)注我的簡書. 其余參考Android目錄.

Intent

本文的合集已經(jīng)編著成書,高級Android開發(fā)強(qiáng)化實(shí)戰(zhàn)衷旅,歡迎各位讀友的建議和指導(dǎo)捐腿。在京東即可購買:https://item.jd.com/12385680.html

Android

在進(jìn)程或頁面通信時(shí)需要使用Intent傳遞數(shù)據(jù); 在對象持久化時(shí)需要存儲數(shù)據(jù). 對于復(fù)雜的對象, 進(jìn)行序列化才可傳遞或存儲, 可以使用Java的Serializable方式或Android的Parcelable方式. 本文介紹SerializableParcelable的使用方式.

本文源碼的GitHub下載地址


Serializable

序列化User類, 實(shí)現(xiàn)Serializable接口即可. 注意serialVersionUID用于輔助序列化與反序列化, 只有相同時(shí), 才會正常進(jìn)行. 如不指定, 則系統(tǒng)會自動生成Hash值, 修改類代碼, 可能會導(dǎo)致無法反序列化, 所以強(qiáng)制指定.

public class UserSerializable implements Serializable {
    // 標(biāo)準(zhǔn)序列ID, 用于判斷版本
    private static final long serialVersionUID = 1L;

    public int userId;
    public String userName;
    public boolean isMale;

    public UserSerializable(int userId, String userName, boolean isMale) {
        this.userId = userId;
        this.userName = userName;
        this.isMale = isMale;
    }
}

序列化對象, 使用ObjectOutputStream存儲已經(jīng)序列化的對象數(shù)據(jù), 通過writeObject寫入對象.

public void serialIn(View view) {
    Context context = view.getContext();
    File cache = new File(context.getCacheDir(), "cache.txt");
    try {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cache));
        UserSerializable user = new UserSerializable(0, "Spike", false);
        out.writeObject(user);
        out.close();
        Toast.makeText(context, "序列化成功", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

緩存文件位置: new File(context.getCacheDir(), "cache.txt").

反序列對象, 使用ObjectInputStream反序列化對象, 通過readObject讀取對象的持久化信息.

public void serialOut(View view) {
    Context context = view.getContext();
    File cache = new File(context.getCacheDir(), "cache.txt");
    UserSerializable newUser = null;
    try {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(cache));
        newUser = (UserSerializable) in.readObject();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(context, "請先序列化", Toast.LENGTH_SHORT).show();

    }
    if (newUser != null) {
        String content = "序號: " + newUser.userId
                + ", 姓名: " + newUser.userName
                + ", 性別: " + (newUser.isMale ? "男" : "女");
        mSerialTvContent.setText(content);
    } else {
        mSerialTvContent.setText("無數(shù)據(jù)");
    }
}

Parcelable

Android推薦的序列化對象方式. 實(shí)現(xiàn)Parcelable接口, writeToParcel寫入對象的變量, UserParcelable提供解析對象方式. CREATOR是創(chuàng)建序列化對象的匿名類, 必須實(shí)現(xiàn), 包含創(chuàng)建單個(gè)對象與數(shù)組的方式. describeContents只有在含有文件描述符是返回1, 默認(rèn)都是返回0, 不需要修改.

public class UserParcelable implements Parcelable {
    public int userId;
    public String userName;
    public boolean isMale;
    public BookParcelable book;

    public UserParcelable(int userId, String userName, boolean isMale, String bookName) {
        this.userId = userId;
        this.userName = userName;
        this.isMale = isMale;
        this.book = new BookParcelable(bookName);
    }

    @Override public int describeContents() {
        return 0;
    }

    @Override public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(userId);
        dest.writeString(userName);
        dest.writeInt(isMale ? 1 : 0);
        dest.writeParcelable(book, 0);
    }

    public static final Parcelable.Creator<UserParcelable> CREATOR = new Parcelable.Creator<UserParcelable>() {
        @Override public UserParcelable createFromParcel(Parcel source) {
            return new UserParcelable(source);
        }

        @Override public UserParcelable[] newArray(int size) {
            return new UserParcelable[size];
        }
    };

    private UserParcelable(Parcel source) {
        userId = source.readInt();
        userName = source.readString();
        isMale = source.readInt() == 1;
        book = source.readParcelable(Thread.currentThread().getContextClassLoader());
    }
}

使用Intent傳遞對象數(shù)據(jù), 編號0, 姓名Spike, 性別女, 喜歡書籍三國演義.

public void parcelSend(View view) {
    Intent intent = new Intent(PASS_PARCEL_FILTER);
    intent.putExtra(PARCEL_EXTRA, new UserParcelable(0, "Spike", false, "三國演義"));
    mLBM.sendBroadcast(intent);
}

解析廣播Intent的數(shù)據(jù), 使用getParcelableExtra方法即可.

private BroadcastReceiver mParcelReceiver = new BroadcastReceiver() {
    @Override public void onReceive(Context context, Intent intent) {
        UserParcelable newUser = intent.getParcelableExtra(PARCEL_EXTRA);
        if (newUser != null) {
            String content = "序號: " + newUser.userId
                    + ", 姓名: " + newUser.userName
                    + ", 性別: " + (newUser.isMale ? "男" : "女")
                    + ", 書: " + newUser.book.bookName;
            Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
            mParcelTvContent.setText(content);
        }
    }
};

效果

動畫

Serializable序列化需要大量的IO操作, Parcelable序列化雖然使用復(fù)雜, 但是效率很高, 是Android開發(fā)的首選. Parcelable主要應(yīng)用于內(nèi)存序列化, 如Intent廣播等.

OK, that's all! Enjoy it!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市芜茵,隨后出現(xiàn)的幾起案子叙量,更是在濱河造成了極大的恐慌倡蝙,老刑警劉巖九串,帶你破解...
    沈念sama閱讀 221,198評論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異寺鸥,居然都是意外死亡猪钮,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評論 3 398
  • 文/潘曉璐 我一進(jìn)店門胆建,熙熙樓的掌柜王于貴愁眉苦臉地迎上來烤低,“玉大人,你說我怎么就攤上這事笆载∑四伲” “怎么了?”我有些...
    開封第一講書人閱讀 167,643評論 0 360
  • 文/不壞的土叔 我叫張陵凉驻,是天一觀的道長腻要。 經(jīng)常有香客問我,道長涝登,這世上最難降的妖魔是什么雄家? 我笑而不...
    開封第一講書人閱讀 59,495評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮胀滚,結(jié)果婚禮上趟济,老公的妹妹穿的比我還像新娘。我一直安慰自己咽笼,他們只是感情好顷编,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著剑刑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上层宫,一...
    開封第一講書人閱讀 52,156評論 1 308
  • 那天,我揣著相機(jī)與錄音限匣,去河邊找鬼。 笑死毁菱,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的贮庞。 我是一名探鬼主播峦筒,決...
    沈念sama閱讀 40,743評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼物喷,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了遮斥?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,659評論 0 276
  • 序言:老撾萬榮一對情侶失蹤术吗,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后较屿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體隧魄,經(jīng)...
    沈念sama閱讀 46,200評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡购啄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評論 3 340
  • 正文 我和宋清朗相戀三年末贾,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拱撵。...
    茶點(diǎn)故事閱讀 40,424評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖拴测,靈堂內(nèi)的尸體忽然破棺而出乓旗,到底是詐尸還是另有隱情集索,我是刑警寧澤汇跨,帶...
    沈念sama閱讀 36,107評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站穷遂,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏娱据。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評論 3 333
  • 文/蒙蒙 一中剩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧结啼,春花似錦掠剑、人聲如沸郊愧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽毅糟。三九已至红选,卻和暖如春姆另,著一層夾襖步出監(jiān)牢的瞬間喇肋,已是汗流浹背迹辐。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留明吩,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,798評論 3 376
  • 正文 我出身青樓印荔,卻偏偏與公主長得像,于是被迫代替她去往敵國和親仍律。 傳聞我的和親對象是個(gè)殘疾皇子嘿悬,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評論 2 359

推薦閱讀更多精彩內(nèi)容