gpt4 book ai didi

java - Android:如何为我的对象实现 Parcelable?

转载 作者:IT老高 更新时间:2023-10-28 23:33:27 24 4
gpt4 key购买 nike

我有一个包含我的 JSON 索引的 ConstantData 类,我需要在带有附加功能的 Activity 之间传递它们。但在此之前,我必须先对这个类的对象实现 Parcelable。

我的问题是,我应该如何在我的类中声明对象并将每个对象放入一个变量中?

我是新手,我现在完全一无所知。谢谢你。随意修改下面的代码。

ConstantData.java

public class ConstantData{

public static String project_title = "project title";
public static String organization_title = "organization title";
public static String keyword = "keyword";
public static String short_code = "short code";
public static String project_description = "description";
public static String smallImageUrl = "smallImageUrl";
public static String bigImageUrl = "bigImageUrl";
public static String price= "price";
public static String country= "country";



public static ArrayList<Project> projectsList = new ArrayList<Project>();


public int describeContents() {
return 0;
}

public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
out.writeString(organization_title);
out.writeString(keyword);
out.writeString(short_code);
out.writeString(project_description);
out.writeString(smallImageUrl);
out.writeString(bigImageUrl);
out.writeString(price);
out.writeString(country);
}

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

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

private ConstantData(Parcel in) {
project_title = in.readString();
organization_title = in.readString();
keyword = in.readString();
short_code = in.readString();
project_description = in.readString();
smallImageUrl = in.readString();
bigImageUrl = in.readString();
price = in.readString();
country = in.readString();
}
}

如果我的问题不够清楚,你可以查这个问题:How to send an object from one Android Activity to another using Intents?

他在那里写了myParcelableObject,我只是不知道如何制作parcelable对象。

编辑Project.java

public class Project {

public String project_title;
public String organization_title;
public String keyword;
public String short_code;
public String project_description;
public String smallImageUrl;
public String bigImageUrl;
public String price;
public String country;
}

最佳答案

需要实现Parcelable接口(interface)

public class ConstantData implements Parcelable {

public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
....
out.writeString(country);
out.writeList(projectsList); // <<--
}

private ConstantData(Parcel in) {
project_title = in.readString();
....
country = in.readString();
projectsList = in.readList();

我认为projectsList的编写工作,Project类也需要实现Parcelable

参见例如this class举个例子。

关于java - Android:如何为我的对象实现 Parcelable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5854791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com