That method is to implement Serializable for the object's class you want to pass to an activity. Then simply pass that serialized object into the intent and grab it when the activity is started. This stackoverflow question does point out its downfalls however, so beware, the most important downfalls for me would be that its slow and can cause increased gc activity. I promise I will spend time with Parcelable and write a blog post on it, and make it as easy as possible to understand!
Here is our custom object we are going to pass to another activity, notice it implements Serializable, this is very important as when we use
putExtra(String name, Serializable value)
in our intent it takes a Serializable parameter.
import java.io.Serializable; public class Present implements Serializable { private final String text; public Present(String text) { this.text = text; } public String getText() { return text; } }Now in the activity class where you start another activity using an intent, use this code.
Present myPresent = new Present ("Red Bike"); Intent intent = new Intent(this, SecondActivity.class); // replace with own Activity class intent.putExtra("present", myPresent); startActivity(intent);From the 'SecondActivity' class you can get the object back by doing this:
Intent intent = getIntent(); Present myPresent = (Present)intent.getSerializableExtra("present"); Log.v("Tag", "My Present is: " + myPresent.getText());Now you should be able to send and receive custom objects to other activities!
No comments:
Post a Comment