简体   繁体   中英

How to send a Calendar object from one activity to another in 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM