gpt4 book ai didi

java - 在 Android 中的 Activity 之间传递对象

转载 作者:行者123 更新时间:2023-11-29 05:38:39 25 4
gpt4 key购买 nike

我有一个对象 Address,它的值如下:name、address、city、state、zip、phone 等。

我使用 HTTP 调用填充对象。这个变量确实被填充了。然后我尝试通过这样做将对象传递给下一个 Activity :

Intent intent = new Intent(NewAddressActivity.this, BuildingTypeActivity.class);
Bundle b = new Bundle();
b.putParcelable("newAddress", (Parcelable)newAddress); // i had to cast 'newAddress' to 'Parcelable' otherwise, it was giving me an error
intent.putExtra("newAddress", b);
startActivity(intent);

在下一个 Activity (BuildingTypeActivity) 中,我像这样获取对象。

Bundle b = this.getIntent().getExtras();
if (b != null) {
Address address = b.getParcelable("newAddress");
}

问题是,当我到达“putParcelable”行时,它总是崩溃。它可能与转换为 Parcelable 有关。所以,我假设这不是传递对象的正确方法?

如能提供有关如何正确传递对象的任何提示,我们将不胜感激。

最佳答案

你需要做这样的事情:

import android.os.Parcel;
import android.os.Parcelable;

public class Address implements Parcelable {

private String name, address, city, state, phone, zip;

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

/*
THE ORDER YOU READ OBJECT FROM AND WRITE OBJECTS TO YOUR PARCEL MUST BE THE SAME
*/

@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(address);
parcel.writeString(city);
parcel.writeString(state);
parcel.writeString(phone);
parcel.writeString(zip);
}


public Address(Parcel p){
name = p.readString();
address = p.readString();
city = p.readString();
state = p.readString();
phone = p.readString();
zip = p.readString();
}

// THIS IS ALSO NECESSARY
public static final Creator<Address> CREATOR = new Creator<Address>() {
@Override
public Address createFromParcel(Parcel parcel) {
return new Address(parcel);
}

@Override
public Address[] newArray(int i) {
return new Address[0];
}
};
}

现在您不必将 newAddress 实例转换为 Parcelable。

关于java - 在 Android 中的 Activity 之间传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18550714/

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