如何将包含任意类型的对象发送到另一个活动?

时间:2014-10-28 03:50:06

标签: java android json android-studio gson

我对Android编程很陌生,我遇到过这个问题。

我有一个对象,我试图发送到一个新的活动,这是这个类的一个实例:

public final class BusinessEntity extends com.google.api.client.json.GenericJson {

/**
 * The value may be {@code null}.
 */
@com.google.api.client.util.Key
private Contact contact;

/**
 * The value may be {@code null}.
 */
@com.google.api.client.util.Key
@com.google.api.client.json.JsonString
private java.lang.Long id;

/**
 * The value may be {@code null}.
 */
@com.google.api.client.util.Key
private java.lang.String imageUrl;

/**
 * The value may be {@code null}.
 */
@com.google.api.client.util.Key
private Person owner;

/**
 * The value may be {@code null}.
 */
@com.google.api.client.util.Key
private java.util.List<java.lang.String> tag;

/**
 * The value may be {@code null}.
 */
@com.google.api.client.util.Key
private java.lang.String type;

我尝试将其转换为gson并将其发送到带有Intent的Bundle中,并将其转换回新Activity中的BusinessEntity问题是我无法在新活动中反序列化它因为它包含对象任意类型。我尝试将其解析为JsonArray,但我得到了异常:&#34; IllegalStateException:这不是JSON数组。&#34;我猜是因为该对象不在集合中。

我希望能够在新的Activity中访问Person和Contact类中的许多属性,但我还想避免单独发送每个属性。

这是我在第一堂课中所拥有的:

Intent i = new Intent(mActivity, DetailsActivity.class);
Bundle b = new Bundle();
Gson gson = new Gson();
String business = gson.toJson(businesses.get(position));
b.putString("business", business); 
i.putExtras(b);
startActivity(i);

这就是我在第二节课中所拥有的:

Bundle b = getIntent().getExtras();
String json = b.getString("business");

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();

Contact contact = gson.fromJson(array.get(0), Contact.class);
Long id = gson.fromJson(array.get(1), Long.class);
String imageURL = gson.fromJson(array.get(2), String.class);
Person person = gson.fromJson(array.get(3), Person.class);
List<String> tag = gson.fromJson(array.get(4), List.class);

但就像我说的那样,我在

处得到一个IllegalStateException

JsonArray array = parser.parse(json).getAsJsonArray();

在我不必单独发送每个属性的情况下,这样做的好方法是什么?

-------------------------------------- EDIT -------- -----------------------------------------------

我尝试了Parcelable,Serializable,Gson,所有内容......每次尝试将对象转换回新活动中的BusinessEntity时,我都会遇到错误。

我创建的解决方法是创建了一个名为SimpleBusiness的新类,它包含BusinessEntity,Contact和Person的所有属性,实现Parcelable,并在其构造函数中将BusinessEntity作为参数。我从BusinessEntity创建一个新的SimpleBusiness对象,我发送到新活动,发送意图,并从新活动的意图中获取它。这是一种奇怪的解决方法,但效果很好。

这是新的课程:

/**
 * BusinessEntity class made with regular objects
 */
public class SimpleBusiness implements Parcelable {

    //Contact
    private String address1;
    private String address2;
    private String city;
    private long contactID;
    private String country;
    private double latitude;
    private double longitude;
    private String phones;
    private String postalCode;
    private String province;

    //BusinessEntity
    private long id;
    private String imageURL;
    private List<String> tag;
    private String type;

    //Person
    private String businessName;
    private String firstName;
    private String lastName;
    private long personId;

    /**
     * Default no-argument constructor
     */
    public SimpleBusiness(){

    }

    /**
     * Constructor taking BusinessEntity as a parameter
     * @param businessEntity
     */
    public SimpleBusiness(BusinessEntity businessEntity) {
        Contact contact = businessEntity.getContact();
        Person person = businessEntity.getOwner();

        address1 = contact.getAddress1();
        address2 = contact.getAddress2();
        city = contact.getCity();
        contactID = contact.getContactId();
        country = contact.getCountry();
        latitude = contact.getLatitude();
        longitude = contact.getLongitude();
        phones = contact.getPhones();
        postalCode = contact.getPostalCode();
        province = contact.getProvince();

        //BusinessEntity
        id = businessEntity.getId();
        imageURL = businessEntity.getImageUrl();
        tag = businessEntity.getTag();
        type = businessEntity.getType();

        //Person
        businessName = person.getBusinessName();
        firstName= person.getFirstName();
        lastName= person.getLastName();
        personId= person.getPersonId();
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public long getContactID() {
        return contactID;
    }

    public void setContactID(long contactID) {
        this.contactID = contactID;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public String getPhones() {
        return phones;
    }

    public void setPhones(String phones) {
        this.phones = phones;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public List<String> getTag() {
        return tag;
    }

    public void setTag(List<String> tag) {
        this.tag = tag;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getBusinessName() {
        return businessName;
    }

    public void setBusinessName(String businessName) {
        this.businessName = businessName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public long getPersonId() {
        return personId;
    }

    public void setPersonId(long personId) {
        this.personId = personId;
    }


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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.address1);
        dest.writeString(this.address2);
        dest.writeString(this.city);
        dest.writeLong(this.contactID);
        dest.writeString(this.country);
        dest.writeDouble(this.latitude);
        dest.writeDouble(this.longitude);
        dest.writeString(this.phones);
        dest.writeString(this.postalCode);
        dest.writeString(this.province);
        dest.writeLong(this.id);
        dest.writeString(this.imageURL);
        dest.writeList(this.tag);
        dest.writeString(this.type);
        dest.writeString(this.businessName);
        dest.writeString(this.firstName);
        dest.writeString(this.lastName);
        dest.writeLong(this.personId);
    }

    private SimpleBusiness(Parcel in) {
        this.address1 = in.readString();
        this.address2 = in.readString();
        this.city = in.readString();
        this.contactID = in.readLong();
        this.country = in.readString();
        this.latitude = in.readDouble();
        this.longitude = in.readDouble();
        this.phones = in.readString();
        this.postalCode = in.readString();
        this.province = in.readString();
        this.id = in.readLong();
        this.imageURL = in.readString();
        this.tag = new ArrayList<String>();
        in.readList(this.tag, List.class.getClassLoader());
        this.type = in.readString();
        this.businessName = in.readString();
        this.firstName = in.readString();
        this.lastName = in.readString();
        this.personId = in.readLong();
    }

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

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

实施:

        Intent i = new Intent(mActivity, DetailsActivity.class);
        Bundle b = new Bundle();

        BusinessEntity business = businesses.get(position);
        SimpleBusiness simpleBusiness = new SimpleBusiness(business);
        i.putExtra("business", simpleBusiness);
        //i.putExtras(b);
        startActivity(i);

在DetailsActivity类中:

        Intent i = getIntent();
        Bundle b = i.getExtras();
        business = (SimpleBusiness)b.get("business");

感谢帮助人员。如果我没有得到你们给我的建议,可能会花费更长的时间。

--------------------------------------------编辑2- -------------------------------------------

切换到直接使用EventBus传递BusinessEntity对象。这么容易多了。 http://www.stevenmarkford.com/passing-objects-between-android-activities/

传递对象:

Intent i = new Intent(mActivity, DetailsActivity.class);
BusinessEntity business = businesses.get(position);
de.greenrobot.event.EventBus.getDefault().postSticky(business);
startActivity(i);

检索对象: @override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.busEntity = (BusinessEntity) EventBus.getDefault().removeStickyEvent(BusinessEntity.class);
    setContentView(R.layout.activity_details);
}

4 个答案:

答案 0 :(得分:0)

如果您能够修改BusinessEntity,请让它实现Serializable。然后,您可以将业务作为额外的业务:

//To put the object as an extra
...
BusinessEntity business = businesses(get(position));
Intent intent = new Intent(mActivity, DetailsActivity.class);
intent.putExtra("business", business); // Where business is now a `Serializable`
...

//To retrieve the object (in your second class). 
//TODO -- Include check to see if intent has the extra first
BusinessEntity retrievedBusiness = (BusinessEntity) intent.getSerializableExtra("business")

答案 1 :(得分:0)

答案 2 :(得分:0)

您可以通过Serializable界面执行此操作。只需让BusinessEntity实现Serializable,就像这样:

public final class BusinessEntity extends com.google.api.client.json.GenericJson implements Serializable {
     //your code here
     ...
     ...
}

然后创建你的意图并额外付诸实践:

Intent i = new Intent(mActivity, DetailsActivity.class);
i.putExtra("BusinessEntity", yourBuisnessEntityObject);
startActivity(i);

最后在你的DetailsActivity中:

BusinessEntity business = (BusinessEntity) getIntent().getSerializableExtra("BusinessEntity");

瞧!您在DetailsActivity中拥有BusinessEntity对象。

修改

回到你的代码,我认为问题是你把 JsonObject 加上 JsonArray 。您应该首先执行与首先发布的相同的操作,但需要进行一次更正:

JsonObject object = parser.parse(json).getAsJsonObject();然后通过键将其解析为JsonObject。

答案 3 :(得分:0)

EventBus使您的生活变得更加轻松,请参阅我对这个问题的回答中的示例和链接:Saving information from one fragment and dialog if the user navigates to another fragment本质上,不需要进行任何序列化或任何事情,只需将对象放在事件总线上并抓住它再次在您的代码中的任何位置(在另一个活动,片段,服务等..)