衫裤跑路 2010-04-29 10:06 采纳率: 50%
浏览 733
已采纳

如何在 Android 上将一个对象从一个活动传递到另一个活动

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

The code for the customer class:

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

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?

转载于:https://stackoverflow.com/questions/2736389/how-to-pass-an-object-from-one-activity-to-another-on-android

  • 写回答

30条回答 默认 最新

  • 关注

    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.

    Pseudocode:

    //To pass:
    intent.putExtra("MyClass", obj);
    
    // To retrieve object in second Activity
    getIntent().getSerializableExtra("MyClass");
    

    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() {}
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题