Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 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 Reply

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...