Thursday, November 29, 2018

java - How to pass an object from one activity to another on Android




I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.



The code for the customer class:



public class Customer {

private String firstName, lastName, Address;
int Age;


public Customer(String fname, String lname, int age, String address) {

firstName = fname;
lastName = lname;
Age = age;
Address = address;
}

public String printValues() {


String data = null;

data = "First Name :" + firstName + " Last Name :" + lastName
+ " Age : " + Age + " Address : " + Address;

return data;
}
}



I want to send its object from one Activity to another and then display the data on the other Activity.



How can I achieve that?


Answer



One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.



Pseudocode:



//To pass:
intent.putExtra("MyClass", obj);


// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");


Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:



class MainClass implements Serializable {

public MainClass() {}


public static class ChildClass implements Serializable {

public ChildClass() {}
}
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...