通过parcelable trough活动获取特定字段

时间:2017-06-29 14:42:07

标签: java android serialization parcelable

我改变了我的类接口以使用parcelable,因为我需要通过一些活动传递一个对象来完成我的工作。

所以我已经实现了一个parcelable类(使用插件来实现):

public class Photo implements Parcelable {
    private int id;
    private Uri image;
    private byte[] cropedImage;
    private String path;
    private Double lat;
    private Double lon;
    private Double alt;
    private String time;

    public Photo() {
    }


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

    public Photo(Uri image, Double lat, Double lon, Double alt, String time) {
        this.image = image;
        this.lat = lat;
        this.lon = lon;
        this.alt = alt;
        this.time = time;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeParcelable(this.image, flags);
        dest.writeByteArray(this.cropedImage);
        dest.writeString(this.path);
        dest.writeValue(this.lat);
        dest.writeValue(this.lon);
        dest.writeValue(this.alt);
        dest.writeString(this.time);
    }

    protected Photo(Parcel in) {
        this.id = in.readInt();
        this.image = in.readParcelable(Uri.class.getClassLoader());
        this.cropedImage = in.createByteArray();
        this.path = in.readString();
        this.lat = (Double) in.readValue(Double.class.getClassLoader());
        this.lon = (Double) in.readValue(Double.class.getClassLoader());
        this.alt = (Double) in.readValue(Double.class.getClassLoader());
        this.time = in.readString();
    }

    public static final Creator<Photo> CREATOR = new Creator<Photo>() {
        @Override
        public Photo createFromParcel(Parcel source) {
            return new Photo(source);
        }

        @Override
        public Photo[] newArray(int size) {
            return new Photo[size];
        }
    };
}

在我的活动中,我创建并填写照片的构造函数,如下所示:

  Photo photo = new Photo(image,location.getLatitude(),location.getLongitude(),location.getAltitude(),data);

        Intent i = new Intent(CameraCapture.this, CropImage.class);
        i.putExtra("Photo",photo);

我将它传递给CropImage活动,在那个活动上我需要检索parcelable并获取特定数据(在这种情况下只是uri)

这就是我所做的:

photo = getIntent().getExtras().getParcelable("Photo");
uri = photo.getImage();

getImage()不存在,我不知道如何检索特定照片对象的parcelable字段,任何帮助?是否有其他方法可以使用parcelable做到这一点,我没有搞清楚?

非常感谢

1 个答案:

答案 0 :(得分:1)

正如我所看到的,您的数据类没有getter和setter,因此请尝试右键单击该类并选择create setter和getter。然后使用这些getter来获取数据

代表。如果你想抽出时间

private String time;
 public String getTime(){    
    return time;
 }