The Difference Between Parcelable And Serializable In Android

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
  1. public class MainActivity extends AppCompatActivity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.   
  8.         findViewById(R.id.button_open).setOnClickListener(new View.OnClickListener() {  
  9.             @Override  
  10.             public void onClick(View v) {  
  11.                 Employee ashish = new Employee(111"Ashish"true);  
  12.                 Intent intent = AnotherActivity.getStartIntent(MainActivity.this);  
  13.                 intent.putExtra("emp", ashish);  
  14.                 startActivity(intent);  
  15.             }  
  16.         });  
  17.   
  18.     }  
  19.   
  20. }  
Another Activity
  1. public class AnotherActivity extends AppCompatActivity {  
  2.     private TextView textView;  
  3.   
  4.     public static Intent getStartIntent(Context context) {  
  5.         Intent intent = new Intent(context, AnotherActivity.class);  
  6.         return intent;  
  7.     }  
  8.   
  9.     @Override  
  10.     protected void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         setContentView(R.layout.activity_another);  
  13.   
  14.         textView = findViewById(R.id.text_emp);  
  15.   
  16.         if (getIntent() != null && getIntent().hasExtra("emp")) {  
  17.             Employee employee = getIntent().getParcelableExtra("emp");  
  18.             String empDetail = employee.getName().concat("\n").concat(employee.isActive() ? "Active" : "Not Active");  
  19.             textView.setText(empDetail);  
  20.         }  
  21.     }