Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a Calendar object from one activity to another in android?

Tags:

java

android

I have a Calendar object having some date and time manually stored in by the user. I want this object to be available for use in the next activity.

How do i do it? The putextra method using Parcelable are giving discrepancies.

like image 498
nihil Avatar asked Dec 19 '12 14:12

nihil


2 Answers

Calendar does not implement Parcelable.

It does look like it implements Serializable however, so you might be able to serialize it down into a string and pass that as an Extra to your other activity.

Another option you have is to use cal.getTimeInMillis() which will give you a long that you can add as an Extra to your intent. Then you can pull it out on the other side and make a new Calendar object and immediately call setTimeInMillis() on it so that it will be set to the same time as the Calendar object in the old activity.

like image 189
FoamyGuy Avatar answered Nov 15 '22 01:11

FoamyGuy


cal.getTimeInMillis() is half right. The problem with just getTimeInMillis() is you lose Timezone information. So a Calendar variable in UTC will be converted to the local timezone when reading that value in, possibly changing the actual date.

I don't know if I have the perfect answer but I saved the time in milliseconds AND the timezone id so I could fully recreate the calendar object on the other side.

public void writeToParcel(Parcel out, int flags) {
    out.writeLong(mycal.getTimeInMillis());
    out.writeString(mycal.getTimeZone().getID());
}

private MyClassObject(Parcel in) {

    long milliseconds = in.readLong();
    String timezone_id = in.readString();

    mycal = new GregorianCalendar(TimeZone.getTimeZone(timezone_id));
    mycal.setTimeInMillis(milliseconds);

}

out.writeSerializable(); is an option but I have read that it is sluggish and does not perform well, so I opted to just avoid it.

like image 41
johnw182 Avatar answered Nov 15 '22 01:11

johnw182