Parcelable 클래스에서 java.util.Date 읽기 및 쓰기


79

Parcelable 클래스에서 일하고 있습니다. java.util.Date이 클래스에서 객체를 읽고 쓸 수 있습니까?

답변:


186

Date가 Serializable 인 경우 writeSerializable을 사용하십시오 . ( 하지만 좋은 생각은 아닙니다. 다른 더 나은 방법은 아래를 참조하십시오 )

@Override
public void writeToParcel(Parcel out, int flags) {
   // Write object
   out.writeSerializable(date_object);

}

private void readFromParcel(Parcel in) {
   // Read object
    date_object = (java.util.Date) in.readSerializable();

}

그러나 직렬화 작업은 많은 성능을 소비합니다. 이것을 어떻게 극복 할 수 있습니까?

따라서 더 나은 사용법은 작성하는 동안 날짜를 Long으로 변환하고 Long을 읽고 Date 생성자에 전달하여 Date를 얻는 것입니다. 아래 코드 참조

   @Override
    public void writeToParcel(Parcel out, int flags) {
       // Write long value of Date
       out.writeLong(date_object.getTime());

    }

    private void readFromParcel(Parcel in) {
       // Read Long value and convert to date
        date_object = new Date(in.readLong());

    }

3
그러나 직렬화 작업은 많은 성능을 소비합니다. 이것을 어떻게 극복 할 수 있습니까?
Mesut 2014 년

1
Serializable은 성능에 좋지 않으며 구형 장치에서 눈에 띄는만큼 longs를 사용하여 수행해야합니다. Joda에는 유용한 도구가 많이 포함되어 있고 내가 종종 더 유용하다고 생각하는 DateTime 개체가 있기 때문에 Joda를 살펴볼 수도 있습니다.
Graham Smith

이제 괜찮습니다. 직렬화하는 대신 long을 사용하는 것을 선호합니다.
Mesut 2014 년

@Mesut 좋아요! 당신은 당신의 해결책을 얻었습니다.
Pankaj Kumar

1
@JockyDoe 그렇지 않습니다. 파 셀링 및 파 셀링 해제 동안의 필드 순서. 따라서 두 필드에 동일한 순서를 사용하고 있는지 확인하십시오.
Pankaj Kumar

18

Kotlin 에서는 가장 간단한 솔루션 인 Parcel 용 확장 프로그램을 만들 수 있습니다.

fun Parcel.writeDate(date: Date?) {
    writeLong(date?.time ?: -1)
}

fun Parcel.readDate(): Date? {
    val long = readLong()
    return if (long != -1L) Date(long) else null
}

그리고 그것을 사용하십시오

parcel.writeDate(date)
parcel.readDate()

14

Long 형식을 얻으려면 date.getTime () 을 사용하십시오 .

public class MiClass implements Parcelable {
    Date date;

    public MiClass(Date date) {
        this.date = date;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(date != null ? date.getTime() : -1);
    }

    protected MiClass(Parcel in) {
        long tmpDate = in.readLong();
        this.date = tmpDate == -1 ? null : new Date(tmpDate);
    }

    public static final Parcelable.Creator<MiClass> CREATOR = new Parcelable.Creator<MiClass>() {
        public MiClass createFromParcel(Parcel source) {
            return new MiClass(source);
        }

        public MiClass[] newArray(int size) {
            return new MiClass[size];
        }
    };
}

이것은 좋은 해결책이지만 1970 년 1 월 1 일 이전의 날짜에는 제대로 작동하지 않습니다. -1L은 실제로 1970 년 1 월 1 일 이전의 1 밀리 초를 나타내는 유효한 값입니다. 따라서 안전성을 높이기 위해 대신 Long.MIN_VALUE와 같은 값을 사용합니다.
BladeCoder

2

이것을 시도하십시오 (Kotlin) :

data class DateParcel(val date: Date?):Parcelable {
constructor(parcel: Parcel) : this(parcel.readValue(Date::class.java.classLoader) as? Date
)

override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeValue(date)
}

override fun describeContents(): Int {
    return 0
}

companion object CREATOR : Parcelable.Creator<DateParcel> {
    override fun createFromParcel(parcel: Parcel): DateParcel {
        return DateParcel(parcel)
    }

    override fun newArray(size: Int): Array<DateParcel?> {
        return arrayOfNulls(size)
    }
}}

1

Date클래스 구현 Serializable...

그래서 당신은 쓸 수 있습니다

parcel.writeSerializable(java.util.Date)

그리고 당신은 다음과 같이 읽을 수 있습니다

java.util.Date date = (java.util.Date)parcel.readSerializable();

1
이것이 작동하는 동안 나는 SO 사용자가 longs를 사용하여 대답을 살펴볼 것을 제안합니다.
Graham Smith

0

다음과 같이 시도하십시오. :

쓰기 ::

yourParse.writeSerializable(YourGivenDate)

읽기 ::

Date myDate = yourParse.readSerializable();
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.