简体   繁体   中英

Passing Object as Argument between Fragments

在此处输入图片说明

This is the Object diagram from the book Big Nerd Ranch Guide - Android Programming. It is for an app that has a list-detail structure.

Here the CrimeLab class holds the ArrayList of the objects that are displayed in the CrimeListFragment. When an item in that ListView is clicked, the Id field of that Crime object is passed to the CrimeActivity which opens the details of that Crime object in the Crime Fragment.

CrimeFragment calls the getCrime(UUID) method of the CrimeLab class to get a reference to that particular Crime object.

My question is, would this be considered the best approach of passing an object's field to another activity and then that activity retrieving the object via the field Extra provided. Should we instead make the Crime class Serializable and directly pass the Crime object from one fragment/activity to another?

Which approach would be considered better and more efficient? Or does it not matter?

I'm sorry if this is a naive question.

With serialization, the object retrieved by the second activity would be an identical, but different object. That means any modification you do on the object in CrimeFragment would not be reflected in the CrimeLab ArrayList, and would be lost once you exit the fragment.

The best approach depends on what you want to do with the object, and the cost of retrieval. In your case, the cost of serialization / deserialization would most certainly outweight the cost of accessing an ArrayList.

Also, implementing Parcelable should be prefered over Serializable on Android for performance reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM