create account

How to pass object between activity using parceler by andrixyz

View this thread on: hive.blogpeakd.comecency.com
· @andrixyz · (edited)
$14.72
How to pass object between activity using parceler
http://www.devapp.it/wordpress/wp-content/uploads/2016/06/parceler-android-642x336.jpg
<a href="http://www.devapp.it/wordpress/wp-content/uploads/2016/06/parceler-android-642x336.jpg">Image Source</a>
#### What Will I Learn?

- Create Model Object in Java
- Serialize Model Class using Parcel 
- Passing data objects between activities

#### Requirements
- Android Studio 
- Java programming language
- Gradle dependency
- Custom serialization using ParcelPropertyConverter

#### Difficulty
- Basic

#### Tutorial Contents
Parceler is a code generation library that generates the Android Parcelable boilerplate source code.  Parceler makes it easy to transfer to data from one activity to another and so on fragment though. Because, when we are developing an Android application usually we always need data when starting a new activity.  Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements. Therefore, we use the parceler and don't have too much code for doing such things like passing data object, data object list, etc.

<b>Integrate project via gradle</b>

First of all we need to define this library to the project first. We will add the dependencies via gradle.
![abc.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1519979417/v3s1rkxtnfagcehopgdb.png)

Click the build.gradle (Module:app) one. Add this line to dependencies section.
```
compile 'org.parceler:parceler-api:1.1.9'
annotationProcessor 'org.parceler:parceler:1.1.9'
``` 
Once you've done, click the sync now  button. 
![dsadds.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1519979621/cpw2uoddxqvrimaaciaq.png)

<b>Creating The Model Class</b>

We need to define our model first. I create some properties using public fields because when we use private fields, the default field serialization strategy as it will incur a performance penalty due to reflection . Of course you can add or change properties depends on your requirements. 
```
public class Task {
    public String id;
    public String title;
    public String detail;
    public String image;
    public int status;
    public User user;
}
```
 After we create the model, don't forget to add the public constructor with no arguments for the annotation library. Once it's done, add the Parcel annotation above of the class to make this model class parcelable.
```
package com.professional.andri.taskmanager.model;

import org.parceler.Parcel;

/**
 * Created by Andri on 19/11/2017.
 */
@Parcel
public class Task {
    public String id;
    public String title;
    public String detail;
    public String image;
    public int status;
    public User user;

    public Task(){

    }

}
```
<b>Passing data between activities</b>

Next, we want to pass a data object from activity to another activity. Now, in  your onCreate method in a activity. Create this task object. 
```
Task task = new Task();
task.title = "Fix payment bugs";
task.detail = "When the customer click the payment method, it display wrong information. Please fix it";
```
Notice that this is a instantiation of a task object. Now, let's continue. We create the intent and put the task using putExtra and use the ```Parcels.wrap``` method. Write these codes. Notice that we put the key "task" that we will use later.

```
Intent intent = new Intent(this, TaskListActivity.class);
intent.putExtra("task", Parcels.wrap(task));
startActivity(intent);
```
To make sure that you have the object instantiated well, you can log it like using this line.
```
Log.d("TAG", "TASK TITLE " + task.title + "TASK DETAIL " + task.detail);
```
After that, go to the logcat and see the messages you have logged before. 

![dasdasd.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520007654/vqbv2iwfe3ckm5esqxac.png)

Notice the highlighted row, that is log that we are printing. Or you can check via debugger, give a line a break point then press the bug icon.

![dasdsadasdsa.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520007790/uir036jgjnghyyydjbuf.png)

After done, we can go to another activity that we put the intent with parcelable earlier. I assume this is TaskListActivity in this post and in onCreate method. We retrieve that value by unwrapping the parcels using the key that we provide before start the activity to this intent. We will log to make sure the data pass to this activity properly. Write down these codes.

```
Task task = Parcels.unwrap(getIntent().getParcelableExtra("task"));
Log.d("TAGGG", "PARCEL: TASK TITLE: " + task.title + " TASK DETAIL " + task.detail);
```
Check the log. You will see something looks like this.

![dsadasdasd.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520008284/lqamkvdg3smu7nsfo1ea.png)

<b>Custom serialization using ParcelPropertyConverter</b>

In some specific case like List or RealmList, we cannot just directly give annotation become parceler. We need something called ParcelPropertyConverter.  Write down this class first. This class is used to convert a RealmList overriding the fromParcel and toParcel method.

```
package com.professional.andri.taskmanager.converter;

import android.os.Parcelable;

import org.parceler.Parcels;
import org.parceler.TypeRangeParcelConverter;

import io.realm.RealmList;
import io.realm.RealmObject;

/**
 * Created by Andri on 2/25/2018.
 */

public class RealmListParcelConverter implements TypeRangeParcelConverter<RealmList<? extends RealmObject>,
        RealmList<? extends RealmObject>>{
    private static final int NULL = -1;

    @Override
    public void toParcel(RealmList<? extends RealmObject> input, android.os.Parcel parcel) {
        parcel.writeInt(input == null ? NULL : input.size());
        if (input != null) {
            for (RealmObject item : input) {
                parcel.writeParcelable(Parcels.wrap(item), 0);
            }
        }
    }

    @Override
    public RealmList fromParcel(android.os.Parcel parcel) {
        int size = parcel.readInt();
        RealmList<Object> list = new RealmList<>();
        for (int i=0; i<size; i++) {
            Parcelable parcelable = parcel.readParcelable(getClass().getClassLoader());
            list.add(Parcels.unwrap(parcelable));
        }
        return list;
    }

}
```
After that, go to the model we created earlier or you can create a new one. In this case i create a new model class call UserRealm that extends RealmObject  and give additional implementation, value and analyze because this is not a basic model class. Add this annotation to the realm list ```@ParcelPropertyConverter(RealmListParcelConverter.class)```. Your class should look like something like this. 
```
package com.professional.andri.taskmanager.realm;

import com.professional.andri.taskmanager.converter.RealmListParcelConverter;

import org.parceler.Parcel;
import org.parceler.ParcelPropertyConverter;

import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.RealmResults;
import io.realm.UserRealmRealmProxy;
import io.realm.annotations.PrimaryKey;

/**
 * Created by Andri on 2/23/2018.
 */

@Parcel(implementations = { UserRealmRealmProxy.class },
        value = Parcel.Serialization.FIELD,
        analyze = { UserRealm.class })
public class UserRealm extends RealmObject {
    @PrimaryKey
    private long id;
    private String level;
    private String name;
    private String username;
    private String password;
    @ParcelPropertyConverter(RealmListParcelConverter.class)
    private RealmList<TaskRealm> tasks;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public RealmList<TaskRealm> getTasks() {
        return tasks;
    }

    public void setTasks(RealmList<TaskRealm> tasks) {
        this.tasks = tasks;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
```
Run again and test the log on your own. It should pass the data correctly. Congratulation, now you can pass datas between activity and using converter to configure more. This kind of passing data is often used in Android development. Thank you for reading this post.



<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@andrixyz/how-to-pass-object-between-activity-using-parceler">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , ,
properties (23)
authorandrixyz
permlinkhow-to-pass-object-between-activity-using-parceler
categoryutopian-io
json_metadata{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":11140459,"name":"parceler","full_name":"johncarl81/parceler","html_url":"https://github.com/johncarl81/parceler","fork":false,"owner":{"login":"johncarl81"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","parceler","android","tutorial","java"],"users":["Parcel","Override","ParcelPropertyConverter","PrimaryKey"],"links":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1519979417/v3s1rkxtnfagcehopgdb.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1519979621/cpw2uoddxqvrimaaciaq.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520007654/vqbv2iwfe3ckm5esqxac.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520007790/uir036jgjnghyyydjbuf.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520008284/lqamkvdg3smu7nsfo1ea.png"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1519979417/v3s1rkxtnfagcehopgdb.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1519979621/cpw2uoddxqvrimaaciaq.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520007654/vqbv2iwfe3ckm5esqxac.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520007790/uir036jgjnghyyydjbuf.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520008284/lqamkvdg3smu7nsfo1ea.png"],"moderator":{"account":"cha0s0000","time":"2018-03-03T00:35:21.882Z","reviewed":true,"pending":false,"flagged":false},"questions":[],"score":0}
created2018-03-02 17:27:30
last_update2018-03-03 00:35:21
depth0
children2
last_payout2018-03-09 17:27:30
cashout_time1969-12-31 23:59:59
total_payout_value10.198 HBD
curator_payout_value4.520 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8,818
author_reputation1,144,619,513,316
root_title"How to pass object between activity using parceler"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id41,683,036
net_rshares3,974,729,685,012
author_curate_reward""
vote details (11)
@cha0s0000 ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorcha0s0000
permlinkre-andrixyz-how-to-pass-object-between-activity-using-parceler-20180303t003532592z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-03 00:35:27
last_update2018-03-03 00:35:27
depth1
children0
last_payout2018-03-10 00:35:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation30,983,518,016,225
root_title"How to pass object between activity using parceler"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id41,755,329
net_rshares0
@utopian-io ·
### Hey @andrixyz I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-andrixyz-how-to-pass-object-between-activity-using-parceler-20180303t093954621z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-03 09:39:54
last_update2018-03-03 09:39:54
depth1
children0
last_payout2018-03-10 09:39:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,506
author_reputation152,955,367,999,756
root_title"How to pass object between activity using parceler"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id41,843,635
net_rshares0