Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

java - How to pass object to another activity

I have a Placemark class that extends from Location class, so I think in this situation I can't use "implements Serializable" here. If anyone know how to use Serializable here, please help me

public class Placemark extends Location

So I start to use Parcelable in other to pass my Placemark object to the second Activity

public class DataPass implements Parcelable{

private Placemark pm;

public DataPass() 
{}

public DataPass(Parcel p)
{
    pm = (Placemark) p.readValue(Placemark.class.getClassLoader());    //<~~ may cause problem here
}

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

@Override
public void writeToParcel(Parcel p, int flags) {
    p.writeValue(pm);
}

public Placemark getPM() {
    return pm;
}

public void setPM(Placemark pm) {
    this.pm = pm;
}

public static Parcelable.Creator<DataPass> CREATOR = new Parcelable.Creator<DataPass>() {

    @Override
    public DataPass createFromParcel(Parcel source) {
        return new DataPass(source);
    }

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

}

Then from current activity I call putExtra(String, Parcelable) and startActivity.

DataPass data = new DataPass();
data.setPM(myPlacemark);
mapintent.putExtra("p", data);
startActivity(mapintent);

And to retrieve it

Bundle bd = getIntent().getExtras();
try {
    DataPass data = bd.getParcelable("p");    //<~~ Exception
    Placemark pm = data.getPM();
} catch (Exception e)
{
    Log.e("error", e.toString());
}

When I run this code I got an exception at DataPass data = bd.getParcelable("p");

cause: ClassCastException
detailMessage: Location cannot be cast to Placemark)

So it's the first problem again when a extends Placemark from Location. I've searched a lot of websites but still can't work out this situation

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1) Instead of

 p.writeValue(pm);

and

pm = (Placemark) p.readValue(Placemark.class.getClassLoader());

try to write:

 p.writeParcelable(pw, 0);

and

pm = (Placemark) p.readParcelable(Placemark.class.getClassLoader());

2) Is your class Placemark implements Parcelable interface?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...