如何通过对象到另一个活动 [英] How to pass object to another activity

查看:188
本文介绍了如何通过对象到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从位置类扩展地标级的,所以我觉得在这种情况下,我不能用实现Se​​rializable在这里。如果有人知道如何在这里使用序列化,请大家帮我

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

于是,我开始使用Parcelable在其他我的地标对象传递给第二个活动

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

}

然后,从当前的活动我打电话putExtra(字符串,Parcelable)和startActivity。

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

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

和检索它

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

当我运行这个code我在得到了一个异常
    DataPass数据= bd.getParcelable(P);

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

推荐答案

您可以创建的应用程序和存储对象那里。
这里的一个例子。

You can create a subclass of Application and store the object there. Here's an example.

这篇关于如何通过对象到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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