在Android中的活动之间传递对象 [英] Passing objects between activities in Android

查看:108
本文介绍了在Android中的活动之间传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象Address,其值如下:姓名,地址,城市,州,邮政编码,电话等.

I have an object Address which has values like: name, address, city, state, zip, phone, etc.

我用HTTP调用填充对象.确实会填充此变量.然后,我尝试通过以下方法将对象传递给下一个活动:

I populate the object with a HTTP call. This variable does get populated. Then I try to pass the object to the next activity by doing so:

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);

在下一个活动(BuildingTypeActivity)中,我像这样获取对象.

And in the next activity (BuildingTypeActivity), I fetch the object like so.

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

问题是,当我到达"putParcelable"行时,它总是崩溃.它可能与强制转换为Parcelable有关.因此,我假设这不是传递对象的正确方法?

The issue is, that it always crashes when I it gets to the 'putParcelable' line. It might have something to do with the cast to to Parcelable. So, I am assuming that this is not the right way to pass objects?

任何有关如何正确传递对象的技巧将不胜感激.

Any tips on how to pass objects properly would be greatly appreciated.

推荐答案

您需要执行以下操作:

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.

And you now shouldn't have to cast your newAddress instance to Parcelable.

这篇关于在Android中的活动之间传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆