如何将Object传递给另一个活动

时间:2018-03-20 14:05:30

标签: android json pojo

我有一个班级$propName = 'BIB1' $i = $ndx = -1 foreach ($obj in $Data.BIBs) { ++$i if ($obj.$propName) { $ndx = $i; break} } $ndx # $ndx now contains the index of the target object or -1 if there was no match

Testendride

public Testendride guranteBoneses;

上设置值
response

我想将此JSONObject jsonObject = new JSONObject(s); Gson gc = new Gson(); guranteBoneses = gc.fromJson(s, Testendride.class); 个对象发送到下一个Testendride

Activity

3 个答案:

答案 0 :(得分:1)

您应该使用Object工具Parcelable 一个简短的例子:

public class MyObject implements Parcelable {

    private final String item1;
    private final String item2;

    public MyObject(String item1, String item2) {
        this.item1 = item1;
        this.item2 = item2;
    }

    public String getItem1() {
        return item1;
    }

    public String getItem2() {
        return item2;
    }

    private MyObject(Parcel in) {
        item1 = in.readString();
        item2 = in.readString();
    }

    public static final Creator<MyObject> CREATOR = new Creator<MyObject>() {
        @Override
        public MyObject createFromParcel(Parcel in) {
            return new MyObject(in);
        }

        @Override
        public MyObject[] newArray(int size) {
            return new MyObject[size];
        }
    };

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(item1);
        dest.writeString(item2);
    }
}  

然后你可以像这样使用你的对象:

MyObject object = new MyObject("first", "second");
intent.putExtra("myObject", object);  

额外使用:intent.getParcelableExtra("myObject");

答案 1 :(得分:0)

您需要将guaranteeBonueses对象转换为parcelable并将其传递给您想要的活动。您可以在此codepath article中阅读有关parcelable的内容 您也可以参考以下文章 https://code.tutsplus.com/tutorials/how-to-pass-data-between-activities-with-android-parcelable--cms-29559

https://www.101apps.co.za/articles/passing-data-between-activities.html

如果您希望将网络响应传递到所需的活动,请选择创建新模型并将其传递,因为分离网络层是一种很好的做法。

答案 2 :(得分:0)

我只是喜欢这个

Gson gc = new Gson();

            Intent intent = new Intent(ActivityGuaranteeBonesesOffers.this, ActivityDetailGaurantee.class);
            intent.putExtra("gurantee","gurantee");

            intent.putExtra("key", gc.toJson(guranteBoneses));

            startActivity(intent);

并在第二个Activity As字符串上接收,然后将其转换为对象类

 Bundle b = new Bundle();
    b = getIntent().getExtras();
    Gson gc = new Gson();
    guranteBoneses = gc.fromJson(b.getString("key"), Testendride.class);