我正在尝试从一个“活动”发送客户类的对象,并在另一个“”中显示它。

客户类别的代码:

public class Customer {

    private String firstName, lastName, address;
    int age;

    public Customer(String fname, String lname, int age, String address) {

        firstName = fname;
        lastName = lname;
        age = age;
        address = address;
    }

    public String printValues() {

        String data = null;

        data = "First Name :" + firstName + " Last Name :" + lastName
        + " Age : " + age + " Address : " + address;

        return data;
    }
}

我想将其对象从一个“活动”发送到另一个“,然后在另一个活动”上显示数据。

我怎样才能做到这一点?


当前回答

我知道静态是不好的,但似乎我们不得不在这里使用它。parceables/seriazables的问题是两个活动具有相同对象的重复实例=内存和CPU的浪费。公共类IntentMailBox{静态队列<对象>content=newLinkedList<对象>();}


呼叫活动

IntentMailBox.content.add(level);
Intent intent = new Intent(LevelsActivity.this, LevelActivity.class);
startActivity(intent);

调用的活动(请注意,当系统销毁和重新创建活动时,可能会多次调用onCreate()和onResume())

if (IntentMailBox.content.size()>0)
    level = (Level) IntentMailBox.content.poll();
else
    // Here you reload what you have saved in onPause()

另一种方法是声明要在该类中传递的类的静态字段。它仅用于此目的。不要忘记,在onCreate中它可以为空,因为系统已经从内存中卸载了应用程序包,并在稍后重新加载。请记住,您仍然需要处理活动生命周期,您可能希望将所有数据直接写入共享的首选项,这对于复杂的数据结构来说是很痛苦的。

其他回答

以上答案几乎都是正确的,但对于那些不理解这些答案的人来说Android有一个强大的类Intent。借助它,您不仅可以在活动之间共享数据,还可以在Android的其他组件之间共享数据(广播接收器,我们使用ContetResolver类无Intent提供的内容服务)。在你的活动中,你建立了意图

Intent intent = new Intent(context,SomeActivity.class);
intent.putExtra("key",value);
startActivity(intent);

在接收活动中

public class SomeActivity extends AppCompactActivity {

    public void onCreate(...){
    ...
          SomeObject someObject = getIntent().getExtras().getParceable("key");
    }
}

为了在活动之间共享,必须在对象上实现Parceable或Serializable接口。很难在对象上实现Parcealbe而不是Serializable接口,这就是为什么android有插件的原因,尤其是针对这一点。下载并使用它。

最好的方法是在应用程序中有一个类(称为Control),该类将保存类型为“Customer”的静态变量(在您的情况下)。初始化活动A中的变量。

例如:

Control.Customer = CustomerClass;

然后转到Activity B并从Control类获取它。使用变量后不要忘记赋值null,否则会浪费内存。

我使用parcelable将数据从一个活动发送到另一个活动。这是我的代码,在我的项目中运行良好。

public class Channel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String uniqueID;
    private String name;
    private String logo;
    private String thumb;


    /**
     * @return The cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *     The cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return The uniqueID
     */
    public String getUniqueID() {
        return uniqueID;
    }

    /**
     * @param uniqueID
     *     The uniqueID to set
     */
    public void setUniqueID(String uniqueID) {
        this.uniqueID = uniqueID;
    }

    /**
     * @return The name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            The name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the logo
     */
    public String getLogo() {
        return logo;
    }

    /**
     * @param logo
     *     The logo to set
     */
    public void setLogo(String logo) {
        this.logo = logo;
    }

    /**
     * @return the thumb
     */
    public String getThumb() {
        return thumb;
    }

    /**
     * @param thumb
     *     The thumb to set
     */
    public void setThumb(String thumb) {
        this.thumb = thumb;
    }


    public Channel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() {
        public Channel createFromParcel(Parcel in) {
            return new Channel(in);
        }

        public Channel[] newArray(int size) {

            return new Channel[size];
        }
    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[5];
        in.readStringArray(result);

        this.cid = result[0];
        this.uniqueID = result[1];
        this.name = result[2];
        this.logo = result[3];
        this.thumb = result[4];
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {

        dest.writeStringArray(new String[] { this.cid, this.uniqueID,
                this.name, this.logo, this.thumb});
    }
}

在活动A中,如下所示:

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("channel",(ArrayList<Channel>) channels);
Intent intent = new Intent(ActivityA.this,ActivityB.class);
intent.putExtras(bundle);
startActivity(intent);

在ActivityB中,使用如下方法获取数据:

Bundle getBundle = this.getIntent().getExtras();
List<Channel> channelsList = getBundle.getParcelableArrayList("channel");

我一直想知道为什么这不能像调用其他活动的方法一样简单。我最近写了一个实用程序库,使它几乎如此简单。你可以在这里查看(https://github.com/noxiouswinter/gnlib_android/wiki/gnlauncher).

GNLauncher使从另一个“活动”等向“活动”发送对象/数据变得简单,就像调用该“活动”中的一个函数并将所需数据作为参数一样。它引入了类型安全性,并消除了所有必须串行化、使用字符串键附加到意图以及在另一端撤消的麻烦。

用法

使用要在要启动的“活动”上调用的方法定义接口。

public interface IPayload {
    public void sayHello(String name, int age);
}

在要启动的“活动”上实现上述界面。当活动准备就绪时,也通知GNLauncher。

public class Activity_1 extends Activity implements IPayload {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Notify GNLauncher when the Activity is ready. 
        GNLauncher.get().ping(this);
    }

    @Override
    public void sayHello(String name, int age) {
        Log.d("gnlib_test", "Hello " + name + "! \nYour age is: " + age);
    }
}

在另一个“活动”中,获取上述“活动”的代理,并使用所需参数调用任何方法。

public class Activity_2 extends Activity {
    public void onClick(View v) {
        ((IPayload)GNLauncher.get().getProxy(this, IPayload.class, Activity_1.class)).sayHello(name, age);
    }
}

将启动第一个活动,并使用所需参数调用方法。

先决条件

请参阅https://github.com/noxiouswinter/gnlib_android/wiki#prerequisites有关如何添加依赖项的信息。

创建类似bean类的类并实现Serializable接口。然后我们可以通过intent方法传递它,例如:

intent.putExtra("class", BeanClass);

然后从其他活动中获取,例如:

BeanClass cb = intent.getSerializableExtra("class");