Passing enum or object through an intent (the best solution) - android

I have an activity that when started needs access to two different ArrayLists. Both Lists are different Objects I have created myself.
Basically I need a way to pass these objects to the activity from an Intent. I can use addExtras() but this requires a Parceable compatible class. I could make my classes to be passed serializable but as I understand this slows down the program.
What are my options?
Can I pass an Enum?
As an aside: is there a way to pass parameters to an Activity Constructor from an Intent?

This is an old question, but everybody fails to mention that Enums are actually Serializable and therefore can perfectly be added to an Intent as an extra. Like this:
public enum AwesomeEnum {
SOMETHING, OTHER;
}
intent.putExtra("AwesomeEnum", AwesomeEnum.SOMETHING);
AwesomeEnum result = (AwesomeEnum) intent.getSerializableExtra("AwesomeEnum");
The suggestion to use static or application-wide variables is a really bad idea. This really couples your activities to a state managing system, and it is hard to maintain, debug and problem bound.
ALTERNATIVES:
A good point was noted by tedzyc about the fact that the solution provided by Oderik gives you an error. However, the alternative offered is a bit cumbersome to use (even using generics).
If you are really worried about the performance of adding the enum to an Intent I propose these alternatives instead:
OPTION 1:
public enum AwesomeEnum {
SOMETHING, OTHER;
private static final String name = AwesomeEnum.class.getName();
public void attachTo(Intent intent) {
intent.putExtra(name, ordinal());
}
public static AwesomeEnum detachFrom(Intent intent) {
if(!intent.hasExtra(name)) throw new IllegalStateException();
return values()[intent.getIntExtra(name, -1)];
}
}
Usage:
// Sender usage
AwesomeEnum.SOMETHING.attachTo(intent);
// Receiver usage
AwesomeEnum result = AwesomeEnum.detachFrom(intent);
OPTION 2:
(generic, reusable and decoupled from the enum)
public final class EnumUtil {
public static class Serializer<T extends Enum<T>> extends Deserializer<T> {
private T victim;
#SuppressWarnings("unchecked")
public Serializer(T victim) {
super((Class<T>) victim.getClass());
this.victim = victim;
}
public void to(Intent intent) {
intent.putExtra(name, victim.ordinal());
}
}
public static class Deserializer<T extends Enum<T>> {
protected Class<T> victimType;
protected String name;
public Deserializer(Class<T> victimType) {
this.victimType = victimType;
this.name = victimType.getName();
}
public T from(Intent intent) {
if (!intent.hasExtra(name)) throw new IllegalStateException();
return victimType.getEnumConstants()[intent.getIntExtra(name, -1)];
}
}
public static <T extends Enum<T>> Deserializer<T> deserialize(Class<T> victim) {
return new Deserializer<T>(victim);
}
public static <T extends Enum<T>> Serializer<T> serialize(T victim) {
return new Serializer<T>(victim);
}
}
Usage:
// Sender usage
EnumUtil.serialize(AwesomeEnum.Something).to(intent);
// Receiver usage
AwesomeEnum result =
EnumUtil.deserialize(AwesomeEnum.class).from(intent);
OPTION 3 (with Kotlin):
It's been a while, but since now we have Kotlin, I thought I would add another option for the new paradigm. Here we can make use of extension functions and reified types (which retains the type when compiling).
inline fun <reified T : Enum<T>> Intent.putExtra(victim: T): Intent =
putExtra(T::class.java.name, victim.ordinal)
inline fun <reified T: Enum<T>> Intent.getEnumExtra(): T? =
getIntExtra(T::class.java.name, -1)
.takeUnless { it == -1 }
?.let { T::class.java.enumConstants[it] }
There are a few benefits of doing it this way.
We don't require the "overhead" of an intermediary object to do the serialization as it's all done in place thanks to inline which will replace the calls with the code inside the function.
The functions are more familiar as they are similar to the SDK ones.
The IDE will autocomplete these functions which means there is no need to have previous knowledge of the utility class.
One of the downsides is that, if we change the order of the Emums, then any old reference will not work. This can be an issue with things like Intents inside pending intents as they may survive updates. However, for the rest of the time, it should be ok.
It's important to note that other solutions, like using the name instead of the position, will also fail if we rename any of the values. Although, in those cases, we get an exception instead of the incorrect Enum value.
Usage:
// Sender usage
intent.putExtra(AwesomeEnum.SOMETHING)
// Receiver usage
val result = intent.getEnumExtra<AwesomeEnum>()

You can make your enum implement Parcelable which is quite easy for enums:
public enum MyEnum implements Parcelable {
VALUE;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeInt(ordinal());
}
public static final Creator<MyEnum> CREATOR = new Creator<MyEnum>() {
#Override
public MyEnum createFromParcel(final Parcel source) {
return MyEnum.values()[source.readInt()];
}
#Override
public MyEnum[] newArray(final int size) {
return new MyEnum[size];
}
};
}
You can then use Intent.putExtra(String, Parcelable).
UPDATE: Please note wreckgar's comment that enum.values() allocates a new array at each call.
UPDATE: Android Studio features a live template ParcelableEnum that implements this solution. (On Windows, use Ctrl+J)

You can pass an enum through as a string.
public enum CountType {
ONE,
TWO,
THREE
}
private CountType count;
count = ONE;
String countString = count.name();
CountType countToo = CountType.valueOf(countString);
Given strings are supported you should be able to pass the value of the enum around with no problem.

For passing an enum by intent, you can convert enum into integer.
Ex:
public enum Num{A ,B}
Sending(enum to integer):
Num send = Num.A;
intent.putExtra("TEST", send.ordinal());
Receiving(integer to enum):
Num rev;
int temp = intent.getIntExtra("TEST", -1);
if(temp >= 0 && temp < Num.values().length)
rev = Num.values()[temp];
Best regards.
:)

If you really need to, you could serialize an enum as a String, using name() and valueOf(String), as follows:
class Example implements Parcelable {
public enum Foo { BAR, BAZ }
public Foo fooValue;
public void writeToParcel(Parcel dest, int flags) {
parcel.writeString(fooValue == null ? null : fooValue.name());
}
public static final Creator<Example> CREATOR = new Creator<Example>() {
public Example createFromParcel(Parcel source) {
Example e = new Example();
String s = source.readString();
if (s != null) e.fooValue = Foo.valueOf(s);
return e;
}
}
}
This obviously doesn't work if your enums have mutable state (which they shouldn't, really).

It may be possible to make your Enum implement Serializable then you can pass it via the Intent, as there is a method for passing it as a serializable. The advice to use int instead of enum is bogus. Enums are used to make your code easier to read and easier to maintain. It would a large step backwards into the dark ages to not be able to use Enums.

Most of the answers that are using Parcelable concept here are in Java code. It is easier to do it in Kotlin.
Just annotate your enum class with #Parcelize and implement Parcelable interface.
#Parcelize
enum class ViewTypes : Parcelable {
TITLE, PRICES, COLORS, SIZES
}

about Oderik's post:
You can make your enum implement Parcelable which is quite easy for enums:
public enum MyEnum implements Parcelable {
...
}
You can than use Intent.putExtra(String, Parcelable).
If you define a MyEnum variable myEnum, then do intent.putExtra("Parcelable1", myEnum), you will get a "The method putExtra(String, Parcelable) is ambiguous for the type Intent" error message.
because there is also a Intent.putExtra(String, Parcelable) method, and original 'Enum' type itself implements the Serializable interface, so compiler does not know choose which method(intent.putExtra(String, Parcelable/or Serializable)).
Suggest that remove the Parcelable interface from MyEnum, and move the core code into wrap class' Parcelable implementation, like this(Father2 is a Parcelable and contain an enum field):
public class Father2 implements Parcelable {
AnotherEnum mAnotherEnum;
int mField;
public Father2(AnotherEnum myEnum, int field) {
mAnotherEnum = myEnum;
mField = field;
}
private Father2(Parcel in) {
mField = in.readInt();
mAnotherEnum = AnotherEnum.values()[in.readInt()];
}
public static final Parcelable.Creator<Father2> CREATOR = new Parcelable.Creator<Father2>() {
public Father2 createFromParcel(Parcel in) {
return new Father2(in);
}
#Override
public Father2[] newArray(int size) {
return new Father2[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mField);
dest.writeInt(mAnotherEnum.ordinal());
}
}
then we can do:
AnotherEnum anotherEnum = AnotherEnum.Z;
intent.putExtra("Serializable2", AnotherEnum.X);
intent.putExtra("Parcelable2", new Father2(AnotherEnum.X, 7));

you can use enum constructor for enum to have primitive data type..
public enum DaysOfWeek {
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
SUNDAY(7);
private int value;
private DaysOfWeek(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
private static final SparseArray<DaysOfWeek> map = new SparseArray<DaysOfWeek>();
static
{
for (DaysOfWeek daysOfWeek : DaysOfWeek.values())
map.put(daysOfWeek.value, daysOfWeek);
}
public static DaysOfWeek from(int value) {
return map.get(value);
}
}
you can use to pass int as extras then pull it from enum using its value.

I like simple.
The Fred activity has two modes -- HAPPY and SAD.
Create a static IntentFactory that creates your Intent for you. Pass it the Mode you want.
The IntentFactory uses the name of the Mode class as the name of the extra.
The IntentFactory converts the Mode to a String using name()
Upon entry into onCreate use this info to convert back to a Mode.
You could use ordinal() and Mode.values() as well. I like strings because I can see them in the debugger.
public class Fred extends Activity {
public static enum Mode {
HAPPY,
SAD,
;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.betting);
Intent intent = getIntent();
Mode mode = Mode.valueOf(getIntent().getStringExtra(Mode.class.getName()));
Toast.makeText(this, "mode="+mode.toString(), Toast.LENGTH_LONG).show();
}
public static Intent IntentFactory(Context context, Mode mode){
Intent intent = new Intent();
intent.setClass(context,Fred.class);
intent.putExtra(Mode.class.getName(),mode.name());
return intent;
}
}

I think your best bet is going to be to convert those lists into something parcelable such as a string (or map?) to get it to the Activity. Then the Activity will have to convert it back to an array.
Implementing custom parcelables is a pain in the neck IMHO so I would avoid it if possible.

Consider Following enum ::
public static enum MyEnum {
ValueA,
ValueB
}
For Passing ::
Intent mainIntent = new Intent(this,MyActivity.class);
mainIntent.putExtra("ENUM_CONST", MyEnum.ValueA);
this.startActivity(mainIntent);
To retrieve back from the intent/bundle/arguments ::
MyEnum myEnum = (MyEnum) intent.getSerializableExtra("ENUM_CONST");

If you just want to send an enum you can do something like:
First declare an enum containing some value(which can be passed through intent):
public enum MyEnum {
ENUM_ZERO(0),
ENUM_ONE(1),
ENUM_TWO(2),
ENUM_THREE(3);
private int intValue;
MyEnum(int intValue) {
this.intValue = intValue;
}
public int getIntValue() {
return intValue;
}
public static MyEnum getEnumByValue(int intValue) {
switch (intValue) {
case 0:
return ENUM_ZERO;
case 1:
return ENUM_ONE;
case 2:
return ENUM_TWO;
case 3:
return ENUM_THREE;
default:
return null;
}
}
}
Then:
intent.putExtra("EnumValue", MyEnum.ENUM_THREE.getIntValue());
And when you want to get it:
NotificationController.MyEnum myEnum = NotificationController.MyEnum.getEnumByValue(intent.getIntExtra("EnumValue",-1);
Piece of cake!

Use Kotlin Extension Functions
inline fun <reified T : Enum<T>> Intent.putExtra(enumVal: T, key: String? = T::class.qualifiedName): Intent =
putExtra(key, enumVal.ordinal)
inline fun <reified T: Enum<T>> Intent.getEnumExtra(key: String? = T::class.qualifiedName): T? =
getIntExtra(key, -1)
.takeUnless { it == -1 }
?.let { T::class.java.enumConstants[it] }
This gives you the flexibility to pass multiple of the same enum type, or default to using the class name.
// Add to gradle
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
// Import the extension functions
import path.to.my.kotlin.script.putExtra
import path.to.my.kotlin.script.getEnumExtra
// To Send
intent.putExtra(MyEnumClass.VALUE)
// To Receive
val result = intent.getEnumExtra<MyEnumClass>()

Don't use enums. Reason #78 to not use enums. :) Use integers, which can easily be remoted through Bundle and Parcelable.

Related

How to pass array or arraylist by intent which has unserializable data?

What I want to do is passing DataModel array between Activity by Intent.
DataModel class has Bitmap object and FirebaseVisionLabel object. I found many sites to implement this.
Many people said that DataModel class should implements Serializable or Parceable interface to pass DataModel[] or ArrayList<DataModel>.
So I tried, but the real problem was FirebaseVisionLabel class cannot be serializable. Also, I cannot modify that class because it is firebase library.
How can I pass DataModel array by intent??
Point
Want to pass array or arraylist of my own class by intent.
that class has unserializable object and I cannot modify.
how can I pass or deal with it?
Use Parceable. It works perfect
public class Test implements Parcelable
{
FirebaseVisionLabel firebaseVisionLabel;
String testString;
protected Test(Parcel in) {
testString = in.readString();
}
public static final Creator<Test> CREATOR = new Creator<Test>() {
#Override
public Test createFromParcel(Parcel in) {
return new Test(in);
}
#Override
public Test[] newArray(int size) {
return new Test[size];
}
};
public FirebaseVisionLabel getFirebaseVisionLabel() {
return firebaseVisionLabel;
}
public void setFirebaseVisionLabel(FirebaseVisionLabel firebaseVisionLabel) {
this.firebaseVisionLabel = firebaseVisionLabel;
}
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(testString);
}
}
After that for passing data through intent
Test test = new Test();
test.setTestString("test");
test.setFirebaseVisionLabel(yourObject);
Intent intent = new Intent(this, BaseActivity.class);
intent.putExtra("key", test);
startActivity(intent);
Use the below code to get ArrayList data without Serialized or Parcelable:
Consider,
Intent intent = new Intent(this, your_second_class.class);
intent.putStringArrayListExtra("<your_name_here>", your_list_here);
startActivity(intent);
Then in your second class use:
Intent i = getIntent();
new_list = i.getStringArrayListExtra("<your_name_here>");
Hope it will work fine.
You may use Application class, which can be used in all the screen, activities.
So store array in Application class and used anywhere in app.
FirebaseVisionLabel doesn't have too many properties. You will need to serialize Label / Confidence /... (anything you care) yourself by creating your own VisionLabelParcelable class.
So far, there are not enough use cases to make ML Kit return a Parcelable FirebaseVisionLabel. Most apps should extract the info they are interested in and pass around if they want.

How can I include a field annotated with #StringDef in a Parcelable?

I have a StringDef annotated interface
#StringDef({
SpecialString.A,
SpecialString.B
})
#Retention(RetentionPolicy.SOURCE)
public #interface SpecialString {
String B = "BBB";
String A = "AAA";
}
Which I use on a field in a parcelable object
public class MyParcelable implements Parcelable {
private final #SpecialString String mType;
protected MyParcelable (Parcel in) {
//Android studio shows an error for this line declaring
//"Must be one of SpecialString.A, SpecialString.B"
mType = in.readString();
}
...
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mType);
}
}
How can I handle parceling a String annotated by #StringDef without resorting to suppressing with //noinspection WrongConstant?
StringDef fields are supported by Parcelable but there is currently no way to ensure the value read back is one of the accepted values.
The method can be safely ignored in Android Studio by adding the comment noinspection WrongConstant
Safer alternatives may be to use an Enum and read it with MyEnum.valueOf(readString) or as CommonsWare suggested, to write an int ordinal or constant instead of the String and do a lookup when the value is read.

Parcelable error sending object from one to another activity

I cant resolve problem when i sending my object "filmovi" to another activity i got a error. when i was tried to send another object "korisnik" it works without any problem.
Error
FATAL EXCEPTION: main
java.lang.ClassCastException: ba.fit.kino.model.filmovi cannot be cast to android.os.Parcelable
Sending from activity
filmovi Film = ((filmovi)lstView.getItemAtPosition(position));
Intent intent = new Intent(getApplicationContext(), RezervacijaActivity.class)
intent.putExtra("Rezervacija", Film);
startActivity(intent);
Reciving in activity
filmovi filmoviRezervacija;
Bundle bundle = getIntent().getExtras();
if(bundle != null){
filmoviRezervacija = bundle.getParcelable.("Rezervacija");
}
I RESOLVE PROBLEM WITHT THIS:
public class filmovi implements Parcelable{......
public filmovi (Parcel source)
{
this.setFilmID(source.readInt());
this.setNaziv(source.readString());
this.setCijenaKarte(source.readFloat());
this.setSalaID(source.readInt());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest,int flags)
{
dest.writeInt(this.filmID);
dest.writeString(this.naziv);
dest.writeFloat(this.cijenaKarte);
dest.writeInt(this.salaID);
}
public static final Parcelable.Creator<filmovi> CREATOR = new Parcelable.Creator<filmovi>() {
#Override
public filmovi createFromParcel(Parcel source) {
return new filmovi(source);
}
#Override
public filmovi[] newArray(int size) {
return new filmovi[size];
}
};
}
The reason is that your filmovi class is not parcelable
To make filmovi, or any class for that matter, parcelable, the class and all of its inner members should
implement the parcelable interface, and implement a writeToParcel method which loosely speaking
streams the class' content.
Here, for example
class MyClass implements parcelable {
private MyMemberDataClass data; <----- must also implement parcelable
void writeToParcel(Parcel dest, int flags) {...}
}
It is not enough that MyClass will implement parcelable.
MyMemberDataClass (i.e. the inner member class) must do so as well.
This may bet complicated. And in many cases it is also not really necessary...
instead, consider using an activity-parameters static object to which you will pass all of
your activity's required params without the need to parcel them!:
filmovi Film = ((filmovi)lstView.getItemAtPosition(position));
Intent intent = new Intent(getApplicationContext(), RezervacijaActivity.class)
RezervacijaActivityParams.setValue(Film); <--------------- instead of putExtra()
startActivity(intent);
Where:
class RezervacijaActivityParams {
private static filmovi Film;
public static void getValue(filmovi f) { Film = f; }
public static filmovi getValue() { return Film; }
}
and in RezervacijaActivity's onCreate:
class RezervacijaActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filmovi = RezervacijaActivityParams.getValue();
RezervacijaActivityParams.setValue(null); <---------- clear static data
}
}
Note, and this is also an answer to kcoppock's comment, that it is a good practice for
your activity to clear the static data immediately after retrieving it.
EDIT: As kcoppock mentioned, you can't place Objects into Intents as extras unless they're serializable or parcelable. Therefore, your Film class will need to implement one of those. I've only ever added native types (int, etc.) to Intents, so I did not know this. Something to watch out for!
As an aside, it's good practice to extract your key strings to static final values. That ensures that the same string ends up in each location you use it.

Parcelable encoder/decoder (External class)

I have an external Java library with a lot of common objects (i.e. User with name, surname, address...). The thing that i want to build up is a (de)serializer class that transforms all my objects into Parcelable objects to send with Intents. The problem is that Android's intents don't support putExtra(String,Parcel) or something similar. Have you got an idea on how to overcome this inconvenient?
Actually I'm putting all my instances in the Application class, but I think it's a dirty method...cleaner one?
You can use putExtras(Bundle extras) method of Intent and implement in your class method exportToBundle() which returns Bundle with values of this object. If you don't want to create any other methods in your class you can create another utility class with static method which converts object of your class to Bundle. And if your class is Parcelable you can put it directly to the Bundle using putParcelable(String key, Parcelable value) method.
You can directly put a Parcelable class into the intent so what you're looking for is supported. There is a word of warning here and I think you've already have this concept down by mentioning serialize / de-serialize. You are sending a copy of the class which will be reconstructed by the class processing the intent. The official android example is weak because only one integer is sent and we can do that already.
Example intent passing a class
Intent intent = new Intent(context, TheClassImCalling.class);
// use a constant that's public or an R string so both the sender
// and receiver are working on the same class
// the class you are sending goes into the putExtra method statement.
intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
mKmlSummary);
startActivity(intent);
You pull a copy out of the class out with a statement like this using the same constant you used to send it.
KMLSummary mkmlSummary = intent.getExtras().getParcelable(
ImageTextListViewActivity.EXTRA_KMLSUMMARY);
Here are the methods that have to be implemented
public class KmlSummary implements Parcelable {
// a constructor with Parcel as argument.
// you read and write the values in the same order.
public KmlSummary(Parcel in) {
this._id = in.readInt();
this._description = in.readString();
this._name = in.readString();
this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
in.readDouble());
this._resrawid = in.readInt();
this._resdrawableid = in.readInt();
this._pathstring = in.readString();
String s = in.readString();
this.set_isThumbCreated(Boolean.parseBoolean(s));
}
// Overridden methods for the Parseable interface.
#Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(this._id);
arg0.writeString(this._description);
arg0.writeString(this._name);
arg0.writeDouble(this.get_bounds().southwest.latitude);
arg0.writeDouble(this.get_bounds().southwest.longitude);
arg0.writeDouble(this.get_bounds().northeast.latitude);
arg0.writeDouble(this.get_bounds().northeast.longitude);
arg0.writeInt(this._resrawid);
arg0.writeInt(this._resdrawableid);
arg0.writeString(this.get_pathstring());
String s = Boolean.toString(this.isThumbCreated());
arg0.writeString(s);
}
#Override
public int describeContents() {
//
return 0;
}
// Some glue to tell the OS how to create the class from the parcel
#SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public KmlSummary createFromParcel(Parcel in) {
return new KmlSummary(in);
}
public KmlSummary[] newArray(int size) {
return new KmlSummary[size];
}
};
}
That's it you can serialize the class into an intent and de-serialize the class from the intent.
Good Luck
Danny117

Is it possible to send a custom object with an Intent as an Extra

I'm asking this question: instread of giving a string, a int and so on, can we push a custom object during the creation fo a new Intent?
newActivity.PutExtra("JsonDataResult", business.getJSON());
In fact I have one object constructed thanks to a JSON (from webrequest) , I parse it and I put it on an object.
At this point I'm passing the string returned from the webrequest to another intent but the parsing takes a long time tu be done, so it could be super-cool the ability to pass custom object with intent.
EDIT : I'm using monodroid / xamarin, so
Android.OS.IParcelable cannot be implemented,
Java.IO.ISerializable cannot be implemented.
You can either let your custom classes implement Parcelable (Google says its faster, but you have to do more coding) or Serializable.
Then add your objects to a bundle (or to the "extra"):
Bundle b = new Bundle()
b.putParcelable("myObject",myObject);
b.putSerializable("myObject",myObject);
For info to Parcelablecheckout this
And if you're interested in the difference between Parcelable and Serializable in more detail check out this
I personally prefer the usage of Serializable for simple object-passing, since the code ist not spoiled with so much code.
Edit: ok isn't your question very similar to this then?
As you've specified you're using Monodroid, it looks like it's not straightforward. I did a quick search and found this forum post
Which listed the following solutions to this problem in Monodroid:
Store the custom Object to be passed as a global variable somewhere, and just read it from your second activity
Which is a bit messy and bad practice, but would work.
Or
serialize your class to a string and send the string to the second Activity
Which will be a little more hard work, but better practice
This is an example how to create a Parcelable class:
public class Person implements Parcelable {
private String name;
private String surname;
private String email;
// Get and Set methods
#Override
public int describeContents() {
return hashCode();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(surname);
dest.writeString(email);
}
// We reconstruct the object reading from the Parcel data
public Person(Parcel p) {
name = p.readString();
surname = p.readString();
email = p.readString();
}
public Person() {}
// We need to add a Creator
public static final Parcelable.Creator<person> CREATOR = new Parcelable.Creator<person>() {
#Override
public Person createFromParcel(Parcel parcel) {
return new Person(parcel);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
Give a look here if you want to use Parcelable.

Categories

Resources