Android what is parcelable

Parcelable. Передаём объекты

Очень часто программисту приходится передавать данные из одной активности в другую. Когда речь идёт о простых типах, то используется метод intent.putExtra() и ему подобные. Данный способ годится для типов String, int, long или массивов. А вот объекты таким образом передать не получится.

В Java существует специальный интерфейс Serializable, но он оказался слишком неповоротлив для мобильных устройств и пользоваться им настоятельно не рекомендуется. Для передачи объектов следует использовать другой интерфейс Parcelable.

В интерфейсе Parcelable используются два метода describeContents() и writeToParcel():

Метод describeContents() описывает различного рода специальные объекты, описывающие интерфейс.

Метод writeToParcel() упаковывает объект для передачи.

Также необходимо реализовать статическое поле Parcelable.Creator CREATOR, которое генерирует объект класса-передатчика.

Напишем пример. Попробуем передать объект «Мои документы». Как известно, признаком настоящего документа являются Усы, лапы, хвост (я ещё добавил бы имя). Создадим новый класс DocumentInfo, который реализует интерфейс Parcelable:

Теперь мы может передать объект через Intent. Создадим две активности. В первой активности напишем код для отправки объекта:

Вторая активность должна принять данные от первой активности:

Получив объект из первой активности, мы можем извлечь необходимые данные и разложить по полочкам.

Если класс слишком большой, то вручную его переделывать утомительно. Существует онлайн-сервис parcelabler а также плагин для Android Studio mcharmas/android-parcelable-intellij-plugin: IntelliJ Plugin for Android Parcelable boilerplate code generation.

Источник

Using Parcelable

Due to Android’s memory management scheme, you will often find yourself needing to communicate with different components of your application, system components, or other applications installed on the phone. Parcelable will help you pass data between these components.

Android uses Binder to facilitate such communication in a highly optimized way. The Binder communicates with Parcels, which is a message container. The Binder marshals the Parcel to be sent, sends and receives it, and then unmarshals it on the other side to reconstruct a copy of the original Parcel.

With the update to kotlin, you can use the plugin kotlin-parcelize Add

to the top of your app’s build.gradle . See kotlin-parcelize for more examples of how to use @Parcelize annotation

The simplest way to create a Parcelable in Java is to use a third-party library called Parceler. See this guide on Parceler to see how to use it. By annotating your Java classes that you intend to use, the library is able to create much of the boilerplate code needed as discussed in the manual steps below.

To allow for your class instances to be sent as a Parcel you must implement the Parcelable interface along with a static field called CREATOR , which itself requires a special constructor in your class.

Here is a typical implementation:

Note that the Parcelable interface has two methods defined: int describeContents() and void writeToParcel(Parcel dest, int flags) . After implementing the Parcelable interface, we need to create the Parcelable.Creator CREATOR constant for our class which requires us to define createFromParcel , newArray .

We can now pass the parcelable data between activities within an intent:

and then access the data in the NewActivity that was launched using:

Now we can access the parcelable data from within the launched activity!

If a launched activity is returning a data result back to the parent activity, the onActivityResult() method in the parent activity is invoked:

Instead of using getIntent() to retrieve the passed object in this case, we access the Intent object via the parameter representing the result (in this example, «data»).

Читайте также:  Ассистент блондинка для андроид

You may notice some similarities between Parcelable and Serializable . DO NOT, I repeat, DO NOT attempt to persist Parcel data. It is meant for high-performance transport and you could lose data by trying to persist it.

Using Parcelable compared to Serializable can achieve up to 10x performance increase in many cases for transport which is why it’s the Android preferred method.

There are a few common gotchas associated to Parcelable to consider below:

One very important thing to pay close attention to is the order that you write and read your values to and from the Parcel. They need to match up in both cases. In my example, I write the int and then the String to the Parcel. Afterwards, I read them in that same exact order. The mechanism that Android uses to read the Parcel is blind and completely trusts you to get the order correct, or else you will run into run-time crashes.

Another problem I have encountered is with ClassNotFound exceptions. This is an issue with the Classloader not finding your class. To fix this you can manually set the Classloader to use. If nothing is set, then it will try the default Classloader which leads to the exception.

As mentioned before you can only put primitives, lists and arrays, Strings, and other Parcelable objects into a Parcel. This means that you cannot store framework dependent objects that are not Parcelable. For example, you could not write a Drawable to a Parcel. To work around this problem, you can instead do something like writing the resource ID of the Drawable as an integer to the Parcel. On the receiving side you can try to rebuild the Drawable using that. Remember, Parcel is supposed to be fast and lightweight! (though it is interesting to see Bitmap implementing Parcelable)

Where is boolean !? For whatever odd reason there is no simple way to write a boolean to a Parcel. To do so, you can instead write a byte with the corresponding value with out.writeByte((byte) (myBoolean ? 1 : 0)); and retrieve it similarly with myBoolean = in.readByte() != 0;

There is a Parcelable plugin that can be imported directly into IntelliJ or Android Studio, which enables you to generate the boilerplate code for creating Parcelables. You can install this plugin by going to Android Studio -> File -> Settings -> Plugins -> Browse repositories :

Источник

Using Android Parcelable Objects

Parcelable is an Android interface that you can use to create parcelable objects. The idea of a parcelable object Android is similar to Serialization in core Java. The differences are the parcelable is more optimized to pass data between activties or fragments in Android, so it is much faster than serialization. A parcelable object does the marshaling and unmarshaling of the data to avoid creating garbage objects.

When implementing a Parcelable interface for a model class, the required methods to implement are describeContents(), writeToParcel() and a constructor with Parcel as the only one parameter, plus a Parcelable.Creator declared as public static final.

The constructor with the Parcel parameter reads the data from Parcel and save it to the class properties. The method writeToParcel as the name suggests, it writes the data to the Parcel for data delivery. One important thing to remember is, the order of the read and write has to be the same in the constructor and the writeToParcel method. For example, if you read string1 first, string2 second and then string3 in the constructor, you have to write string1 first, string2 second and then string3 in the writeToParcel method.

Читайте также:  Как включить права root для android

A simple Parcelable class with only primitive data fields, Major.java

A Parcelable class with a Parcelable object as one of the data field. This kind of Parcelable class is also called nested parcelable class. Student.java, the special lines are dest.writeParcelable(this.mMajor, flags); and this.mMajor = in.readParcelable(Major.class.getClassLoader()); . Important to remember: The parcelable object has to be the first one in the read and write

A Parcelable class with one of the class field being an ArrayList of another Parcelable objects. Teacher.java, a teacher can have multiple students. The special lines are dest.writeTypedList(this.mStudents); and in.readTypedList(this.mStudents, Student.CREATOR);

Create some dummy Parcelable object using the above Parcelable classes.

To pass the above student parcelable to an activity class, for example AnStudentViewActivity class

To get student parcelable in the AnStudentViewActivity class, in the onCreate method

Источник

Parcelable Android Example

Parcelable is a serialization mechanism provided by Android to pass complex data from one activity to another activity.In order to write an object to a Parcel, that object should implement the interface “ Parcelable “.

In this post, we will see how to implement a Parcelable object in an Android application to pass complex data from one activity to another activity.
To make an object Parcelable we have to implement two methods defined in Parcelable interface:

Methods of Parcelable interface

describeContents()
writeToParcel(Parcel dest, int flags)

We have to provide Parcelable. A creator that is used to create an instance of the class from the Parcel data.

Let get into the example program for Parcelable.
Consider the same class User with user details

writeToParcel
Writetoparcel method we simply write all the class attributes.

Parcel.Creator
And in the Parcel. Creator, we read the parcel data.

Now the User object is ready to pass from one activity to another activity.I am going to pass this User object from my MainActivity to UserActivity using the Intent.

In my another activity I am receiving the Parcel from the Intent,

Источник

Parcelable vs Serializable

Apr 23, 2017 · 4 min read

Often, when we develop applications, we have to transfer data from one Activity to another. Of course, we can not do that directly. The data we want to transfer must be included into a corresponding Intent object. And if we want to move a complex POJO (e.x. Person, Car, Employee, etc.) we also need to perform some additional actions to make that object suitable for a transfer. To do that, our object must be either Serializable or Parcelable.

What is Serializable?

Serializable is a stan d ard Java interface. It is not a part of the Android SDK. It’s simplicity is it’s beauty. Just by implementing this interface your POJO will be ready to jump from one Activity to another. In the following code snippet you can see how simple it is to use this interface.

Because Serializable is a marker interface, we don’t have to implement tons of extra methods. When we ‘mark’ our POJO with it, Java will try it’s best to serialize it.

Of course, this simple approach has it’s price. Reflection is used during the process and lots of additional objects are created along the way. This can cause lot’s of garbage collection. The result is poor performance and battery drain.

Читайте также:  Амнезия призрак прошлого для андроид

What is Parcelable?

Parcelable is another interface. Despite it’s rival (Serializable in case you forgot), it is a part of the Android SDK. Now, Parcelable was specifically designed in such a way that there is no reflection when using it. That is because, we are being really explicit for the serialization process. In the code snippet down below you can see a sample usage of the Parcelable interface:

Of course, there is a price we have to pay when using Parcelable as well! Because of the boilerplate code, it is much harder to maintain and understand the POJO from above.

Parcelable VS Serializable

If you search through the web for info on this topic, you will most probably come to the conclusion that there won’t be an absolute winner for this comparison. There are people and articles out there, which support either the one, or the other approach. Thus, I will present you both sides and leave you to decide for yourself!

The first ‘team’ stands behind the idea that Parcelable is way faster and better than Serializable. Of course, there is data behind this statement.

The results from the tests conducted by Philippe Breault show that Parcelable is more than 10x faster than Serializable. Some other Google engineers stand behind this statement as well.

You can find a link to Philippe’s article in the ‘References’ section down below.

Now, the second ‘team’ claims that we are all doing it wrong! And their arguments sound reasonable enough!

According to them, the default Serializable approach is slower than Parcelable. And here we have an agreement between the two parties! BUT, it is unfair to compare these two at all! Because with Parcelable we are actually writing custom code. Code specifically created for that one POJO. Thus, no garbage is created and the results are better. But with the default Serializable approach, we rely on the automatic serialization process of Java. The process is apparently not custom at all and creates lots of garbage! Thus, the worse results.

Now, there is another approach. The whole automatic process behind Serializable can be replaced by custom code which uses writeObject() & readObject() methods. These methods are specific. If we want to rely on the Serializable approach in combination with custom serialization behavior, then we must include these two methods with the same exact signature as the one below:

Strange! Weird! Unusual! But that’s how it works! Now, in these two methods we can include our custom logic. If done correctly, the garbage associated with the default Serializable approach will not be a factor anymore!

And now a comparison between Parcelable and custom Serializable seems fair! The results may be surprising! The custom Serializable approach is more than 3x faster for writes and 1.6x faster for reads than Parcelable. You can find a BitBucket project with test data in the ‘Resources’ section to play with.

In my opinion, the differences in speed between the two approaches will be almost insignificant in most of the cases. Thus, at the end of the day, it is rather more important to get the job done and to have happy users, than to have an app running with 0.000042 milliseconds faster.

Источник

Оцените статью