[英]How to access an element of an ArrayList inside Parcelable object?
尝试对我的许多对象实施Parcelable时遇到了麻烦。 到目前为止,我有一个包含所有String和integer变量的Project类,以及另一个名为ParcelableProject的对象,其中包含一个Project类。 当我尝试使用AllProjects的名称创建另一个Parcelable类时,我的困难就开始了,该类包含一个由ParcelableProject对象组成的单个数组列表。
我有通过意图移动项目的这种方法:
public void addProject(ParcelableProject p){
Intent i = new Intent(this.getActivity(), ProjectsFragment.class);
ArrayList<ParcelableProject> data = new ArrayList<ParcelableProject>();
data.add(p);
i.putParcelableArrayListExtra("projects", data);
}
此外,在我的ProjectsFragment中,我尝试通过以下方式访问此ArrayList数据:
Intent i = getActivity().getIntent();
Bundle data=i.getExtras();
ArrayList Projects= data.getParcelable("projects");
ParcelableProject pProj=Projects.get(0);
但这给了我“无法从Object转换为ParcelableProject”错误。 访问项目变量的正确方法是什么? 将有一个传递给我的ProjectsFragment的列表,因此Parcelable需要包含一个ArrayList of Projects,我只是不知道如何访问单个项目。
这样做
Intent i = getIntent();
Bundle data=i.getExtras();
ArrayList<ParcelableProject> Projects= (ArrayList<ParcelableProject>) data.getParcelable("projects");
更新尝试这个
ArrayList<ParcelableProject> Projects= (ArrayList<ParcelableProject>) data.getParcelableArrayList("projects");
尝试这个
public class EmployeeData implements Parcelable {
String empName;
String empId;
String empAddress;
public EmployeeData(Parcel in) {
readFromParcel(in);
}
public EmployeeData(String name, String id, String address) {
this.empName = name;
this.empId = id;
this.empAddress = address;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
private void readFromParcel(Parcel in) {
empName = in.readString();
empId = in.readString();
empAddress = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(empName);
dest.writeString(empId);
dest.writeString(empAddress);
}
public static final Parcelable.Creator<EmployeeData> CREATOR = new Creator<EmployeeData>() {
@Override
public EmployeeData[] newArray(int size) {
// TODO Auto-generated method stub
return new EmployeeData[size];
}
@Override
public EmployeeData createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new EmployeeData(source);
}
};
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
}
像这样放置对象:
EmployeeData empData = new EmployeeData(name, id, address);
Bundle bundle = new Bundle();
bundle.putParcelable("DATA", empData);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtras(bundle);
得到像这样的对象:
EmployeeData empData = getIntent().getParcelableExtra("DATA");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.