26 Şubat 2018 Pazartesi

Parcelable Arayüzü

Giriş
Şu satırı dahil ederiz.
import android.os.Parcelable;
Açıklaması şöyle.
1. Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.
2. Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.
Bir başka açıklama şöyle
Parcelable is used for complex models.
Parcelable aslında serializable gibi düşünülmeli.

IDE'ler model sınıflarımız için Parcelable Code Generator plugin'leri sunuyor. Elle kodlamak yerine bunları kullanmak daha iyi.

Tanımlama
Şöyle yaparız.
class Car implements Parcelable {
  public int regId;
  public String brand;
  public String color;

private Car(Parcel source) {
  regId = source.readInt();
  brand = source.readString();
  color = source.readString();
}

public Car(int regId, String brand, String color) { 
  this.regId = regId;
  this.brand = brand;
  this.color = color;
}

public int describeContents() {
  return this.hashCode();
}

public void writeToParcel(Parcel dest, int flags) {
  dest.writeInt(regId);
  dest.writeString(brand);
  dest.writeString(color);
}

public static final Parcelable.Creator CREATOR
         = new Parcelable.Creator() {
  public Car createFromParcel(Parcel in) {
    return new Car(in);
  }

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

CREATOR Alanı
Sınıfımızı Parcel'den yaratabilmek için gerekir. Şöyle yaparız.
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
  public Student createFromParcel(Parcel in) {
    return new Student(in); 
  }

  public Student[] newArray(int size) {
    return new Student[size];
  }
};
describeContents metodu
Kalıtan sınıf tarafından override edilir. Kalıtan sınıfta şöyle yaparız.
@Overridepublic int describeContents(){
  return 0;
}
writeToParcel metodu
Kalıtan sınıf tarafından override edilir. Serialization işlemini gerçekleştirilir. Kalıtan sınıfta şöyle yaparız.
@Override
public void writeToParcel(Parcel dest, int flags) {
  dest.writeStringArray(new String[] {this.id,
                                      this.name,
                                      this.grade});
}



Hiç yorum yok:

Yorum Gönder