Pass a custom class from one activity to another using Intent

In this article, I am going to discuss about sending a custom class from one activity to another or any custom class to send from one activity to another using Intent.

We can pass a custom class using two ways, rather using two interfaces that are provided by Android which are java.io.Serializable and android.os.Parcelable.

First create a custom class then implements the class with Serializable interface. To make the class serializable include two functions, which are writeObject() and readObject(). Whatever objects we need to pass has to write to the ObjectOutputStream in writeObject() and we have to read from readObject() using ObjectInputStream.
public class MyClass implements Serializable {
     
     String firstName;
     int empID;
     
     public MyClass(String name, int id) {
      firstName = name;
      empID = id;
     }
     
     private void writeObject(ObjectOutputStream out) {
      try {
    out.writeUTF(firstName);
   } catch (IOException e) {
    e.printStackTrace();
   }
     }
     
     private void readObject(ObjectInputStream in) {
      try {
    firstName = in.readUTF();
   } catch (IOException e) {
    e.printStackTrace();
   }
     }
     
     public String getName() {
      return firstName;
     }
     
     public int getEmpId() {
      return empID;
     }
    }
Next step is create an object of the custom class and put it into the intent using putExtra(). In the next activity we can get the custom class object using getIntent().getSerializableExtra()

You can get the full source code from here

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android