larry*wei 2010-04-29 10:06 采纳率: 0%
浏览 626
已采纳

如何在 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条回答 默认 最新

  • 狐狸.fox 2010-04-29 10:39
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效