我想将对象oManagement
从活动X传递给Y.
在X:
oManagement = new OrdersManagement();
myIntent = new Intent(this, Y.class);
然后我用单独的线程填充我的oManagement对象。
然后我等待oManagement填写并开始另一项活动:
while (oManagement.allOrders.size() == 0) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (oManagement.allOrders.size() > 0) {
myIntent.putExtra("OrdersManagementObject", oManagement);
this.startActivity(myIntent);
}
}
在我的Y活动中:
Bundle b = this.getIntent().getExtras();
if (b != null) {
oManagement = b.getParcelable("OrdersManagementObject");
}
现在惊喜 - > oManagement
不是null
,但是oManagement.allOrders.size()
是0! :(所以我传递了我的对象,但是ArrayList
里面的对象是0(在传递的时刻是该数组中的1个元素)。
如何解决这个问题?
编辑:
OrdersManagement类:
public class OrdersManagement implements Parcelable {
public ArrayList<QuantorsOrder> allOrders = new ArrayList<QuantorsOrder>();
public OrdersManagement() {
}
public OrdersManagement(Parcel in) {
}
public static final Creator<OrdersManagement> CREATOR = new Creator<OrdersManagement>() {
@Override
public OrdersManagement createFromParcel(Parcel in) {
return new OrdersManagement(in);
}
@Override
public OrdersManagement[] newArray(int size) {
return new OrdersManagement[size];
}
};
public void updateListOfOrders(JSONArray jsonArray) throws JSONException {
if (jsonArray != null && jsonArray.length() > 0)
{
JSONObject json;
for (int i = 0; i < jsonArray.length(); i++)
{
json = (JSONObject)jsonArray.get(i);
if(!IsOrderAlreadyExists(json))
addOrder(json);
}
}
}
private boolean IsOrderAlreadyExists(JSONObject json) throws JSONException
{
if (allOrders.isEmpty())
return false;
else
{
for(QuantorsOrder order : allOrders)
{
if (String.valueOf(order.getId()).equals(json.get("id").toString()))
{
return true;
}
}
return false;
}
}
private void addOrder(JSONObject json) throws JSONException {
allOrders.add(new QuantorsOrder(json));
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
}
答案 0 :(得分:2)
您的QuantorsOrder
也应该实施Parcelable。
在writeToParcel()
方法中,您应该编写列表并在构造函数中读取它,如下所示:
public void writeToParcel(Parcel out, int flags) {
out.writeTypedList(allOrders);
}
private OrdersManagement (Parcel in) {
in.readTypedList(allOrders, QuantorsOrder.CREATOR);
}
您还应该在QuantorsOrder
课程中实现写作和阅读字段的逻辑。
以下是简单类的示例:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
public MyParcelable(Parcel in) {
mData = in.readInt();
}
}
这里的主要内容发生在writeToParcel(...)
方法和构造函数public MyParcelable(Parcel in)
中。