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

客户类别的代码:

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

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

我怎样才能做到这一点?


当前回答

您还可以将对象的数据写入临时字符串和int,并将它们传递给活动。当然,这样可以得到传输的数据,但不能得到对象本身。

但是,如果您只想显示它们,而不在其他方法或类似方法中使用对象,那么就足够了。我以同样的方式在另一个活动中显示一个对象的数据。

String fName_temp   = yourObject.getFname();
String lName_temp   = yourObject.getLname();
String age_temp     = yourObject.getAge();
String address_temp = yourObject.getAddress();

Intent i = new Intent(this, ToClass.class);
i.putExtra("fname", fName_temp);
i.putExtra("lname", lName_temp);
i.putExtra("age", age_temp);
i.putExtra("address", address_temp);

startActivity(i);

你也可以直接传递它们,而不是传递临时变量,但在我看来,这样更清楚。此外,您可以将temp ivars设置为null,以便GarbageCollector更快地清理它们。

祝你好运

附带说明:重写toString()而不是编写自己的打印方法。

正如下面的评论中提到的,这是您在另一个活动中获取数据的方式:

String fName = getIntent().getExtras().getInt("fname");

其他回答

这个问题也在另一个堆栈溢出问题中讨论。请查看使用Serializable通过意向传递数据的解决方案。重点是使用Bundle对象,它在Intent中存储必要的数据。

 Bundle bundle = new Bundle();

 bundle.putSerializable(key1, value1);
 bundle.putSerializable(key2, value2);
 bundle.putSerializable(key3, value3);

 intent.putExtras(bundle);

要提取值,请执行以下操作:

 Bundle bundle = new Bundle();

 for (String key : bundle.keySet()) {
 value = bundle.getSerializable(key));
 }

Serializable的优点是简单。然而,如果需要传输许多数据,您应该考虑使用Parcelable方法,因为Parcelable是专门为Android设计的,它比Serializable更高效。可以使用以下命令创建Parcelable类:

在线工具parcelablerAndroid Studio插件-Android Parcelable代码生成器

我使用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");

正如在评论中提到的,这个答案打破了封装并紧密耦合了组件,这很可能不是您想要的。最好的解决方案可能是使对象可Parcelable或Serializable,正如其他响应所解释的那样。话虽如此,解决方案解决了问题。所以,如果你知道你在做什么:

使用带有静态字段的类:

public class Globals {
    public static Customer customer = new Customer();
}

在活动内部,您可以使用:

活动来源:

Globals.customer = myCustomerFromActivity;

活动目标:

myCustomerTo = Globals.customer;

这是传递活动信息的简单方法。

我创建了一个保存临时对象的单例助手类。

public class IntentHelper {

    private static IntentHelper _instance;
    private Hashtable<String, Object> _hash;

    private IntentHelper() {
        _hash = new Hashtable<String, Object>();
    }

    private static IntentHelper getInstance() {
        if(_instance==null) {
            _instance = new IntentHelper();
        }
        return _instance;
    }

    public static void addObjectForKey(Object object, String key) {
        getInstance()._hash.put(key, object);
    }

    public static Object getObjectForKey(String key) {
        IntentHelper helper = getInstance();
        Object data = helper._hash.get(key);
        helper._hash.remove(key);
        helper = null;
        return data;
    }
}

不要将对象放在Intent中,而是使用IntentHelper:

IntentHelper.addObjectForKey(obj, "key");

在新的“活动”中,您可以获取对象:

Object obj = (Object) IntentHelper.getObjectForKey("key");

请记住,一旦加载,对象将被删除,以避免不必要的引用。

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

实际代码:

在自定义模型/对象类中:

public class YourClass implements Serializable {

在使用自定义模型/类的其他类中:

//To pass:
intent.putExtra("KEY_NAME", myObject);

myObject的类型为“YourClass”。然后,要从另一个活动中检索,请使用getSerializableExtra使用相同的Key名称获取对象。需要对YourClass进行类型转换:

// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");

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

class MainClass implements Serializable {
    
    public MainClass() {}

    public static class ChildClass implements Serializable {
         
        public ChildClass() {}
    }
}