如何在Android上将对象从一个活动传递到另一个活动 [英] How to pass an object from one activity to another on Android

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

问题描述

我正在尝试从一个 Activity 发送我的 customer 类的对象,并在另一个 Activity 中显示它.

I am trying to work on sending an object of my customer class from one Activity and display it in another 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 上显示数据.

I want to send its object from one Activity to another and then display the data on the other Activity.

我怎样才能做到这一点?

How can I achieve that?

推荐答案

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

One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.

伪代码:

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

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

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

Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:

class MainClass implements Serializable {

    public MainClass() {}

    public static class ChildClass implements Serializable {

        public ChildClass() {}
    }
}

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

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