问题

我正在尝试从一个Activity发送mycustomerclass的对象并将其显示在另一个Activity中。

客户类的代码:

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

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

我怎样才能做到这一点?


#1 热门回答(712 赞)

一个选项可能是让你的自定义类实现Serializable接口,然后你可以使用Intent#putExtra()方法的putExtra(Serializable ..)变体在intent extra中传递对象实例。

伪代码

//To pass:
intent.putExtra("MyClass", obj);

// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");

注意:确保主自定义类的每个嵌套类都已实现Serializable接口,以避免任何序列化异常。例如:

class MainClass implements Serializable {

    public MainClass() {}

    public static class ChildClass implements Serializable {

        public ChildClass() {}
    }
}

#2 热门回答(259 赞)

使用Serializable实现你的类。我们假设这是你的实体类:

import java.io.Serializable;

@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class Deneme implements Serializable {

    public Deneme(double id, String name) {
        this.id = id;
        this.name = name;
    }

    public double getId() {
        return id;
    }

    public void setId(double id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private double id;
    private String name;
}

我们将名为dene的对象从X活动发送到Y活动。 X活动的某个地方;

Deneme dene = new Deneme(4,"Mustafa");
Intent i = new Intent(this, Y.class);
i.putExtra("sampleObject", dene);
startActivity(i);

在Y活动中,我们得到了对象。

Intent i = getIntent();
Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");

而已。


#3 热门回答(102 赞)

  • 使用全局静态变量不是一个好的软件工程实践。
  • 将对象的字段转换为原始数据类型可能是一项繁忙的工作。
  • 使用serializable是可以的,但它在Android平台上效率不高。
  • Parcelable是专为Android设计的,你应该使用它。这是一个简单的示例:在Android活动之间传递自定义对象

你可以使用thissite为你的类生成Parcelable代码。


原文链接