简体   繁体   中英

Passing objects between activities in Android

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

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

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

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.

You'll need to do something like this:

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];
        }
    };
}

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

For casting an object to Parcelable , your class for that object should be Parcelable . Hence you need to implement Parcelable interface as suggested above.

您可以使用serializable来完成工作..这是最简单的方法...... 在这里

EDIT: just realised it's very old post :)

Parcelable is best practice but yeah tedious to write code and maintain it. This site can be a helping hand for this

Parcelabler

Note: I haven't tried the Parcelable created with this, as I didn't face the need, but yeah worth a try

You can easily pass objects within intents using Serializable interface. For this purpose, the object you are passing should be an instance of class implementing Serializable interface. Here is a simple example to pass an object from one Intent to another. In this example, the object testObject of class TestClass has been passed from MainActivity to NewActivity .

activity_main.xml:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Here"
    android:id="@+id/button"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:onClick="changeIntent" />

activity_new.xml:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Medium Text"
    android:id="@+id/textView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

MainActivity.java:

package com.example.nabin.serializabledemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;

public class MainActivity extends ActionBarActivity {
    TestClass testObject;
    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testObject = new TestClass("Name");
    }
    public void changeIntent(View v){
        intent = new Intent(MainActivity.this,NewActivity.class);
        intent.putExtra("sampleObject", testObject);
        startActivity(intent);
    }
}

TestClass.java:

package com.example.nabin.serializabledemo;

import java.io.Serializable;

public class TestClass implements Serializable{
    String classname;
    int no = 1;
    String [] sampleArray = {"Apple", "Banana"};
    public TestClass(String name){
        classname = name;
    }
}

NewActivity.java:

package com.example.nabin.serializabledemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;

public class NewActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new);
        Intent i = getIntent();
        TestClass tc = (TestClass)i.getSerializableExtra("sampleObject");
        String name = tc.classname;
        int no = tc.no;
        String [] array = tc.sampleArray;
        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText("Name: "+name+"\nno: "+no+"\nArray: "+ array[0]+" " + array[1]);
    }
}

Hope this example will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM