Why do we serialize objects?
Serialization of the object is usually needed when you send your object over a network or store it in files because the network infrastructure and hardware components used for storage understand bits and bytes, but not objects. In Android, when you want to send an object to another activity from any activity, you cannot send it as you do in primitive types.
Difference
-
Serializable interface is very easy to implement. It is a marker interface and by implementing this, your POJO class is able to be serialized and deserialized; whereas Parcelable is not a marker interface, hence it has some methods that you will have to override when you implement this in your class.
-
Serializable interface is not a part of Android SDK and it uses reflection for marshaling operations and creates lots of temp objects. In Parcelable, you are able to choose which field you want to serialize.
-
Because of the temp object creation and garbage collection, Serialization is slower than Parcelable.
Below is the code.
MainActivity
- public class MainActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- findViewById(R.id.button_open).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Employee ashish = new Employee(111, "Ashish", true);
- Intent intent = AnotherActivity.getStartIntent(MainActivity.this);
- intent.putExtra("emp", ashish);
- startActivity(intent);
- }
- });
-
- }
-
- }
Another Activity
- public class AnotherActivity extends AppCompatActivity {
- private TextView textView;
-
- public static Intent getStartIntent(Context context) {
- Intent intent = new Intent(context, AnotherActivity.class);
- return intent;
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_another);
-
- textView = findViewById(R.id.text_emp);
-
- if (getIntent() != null && getIntent().hasExtra("emp")) {
- Employee employee = getIntent().getParcelableExtra("emp");
- String empDetail = employee.getName().concat("\n").concat(employee.isActive() ? "Active" : "Not Active");
- textView.setText(empDetail);
- }
- }
- }