How to pass an object from one activity to another on Android

后端 未结 30 4143
遇见更好的自我
遇见更好的自我 2020-11-21 04:03

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 t

30条回答
  •  猫巷女王i
    2020-11-21 05:01

    Create your own class Customer as following:

    import import java.io.Serializable;
    public class Customer implements Serializable
    {
        private String name;
        private String city;
    
        public Customer()
        {
    
        }
        public Customer(String name, String city)
        {
            this.name= name;
            this.city=city;
        }
        public String getName() 
        {
            return name;
        }
        public void setName(String name) 
        {
            this.name = name;
        }
        public String getCity() 
        {
            return city;
        }
        public void setCity(String city) 
        {
            this.city= city;
        }
    
    }
    

    In your onCreate() method

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_top);
    
        Customer cust=new Customer();
        cust.setName("abc");
        cust.setCity("xyz");
    
        Intent intent=new Intent(abc.this,xyz.class);
        intent.putExtra("bundle",cust);
        startActivity(intent); 
    }
    

    In xyz activity class you need to use the following code:

    Intent intent=getIntent();
    Customer cust=(Customer)intent.getSerializableExtra("bundle");
    textViewName.setText(cust.getName());
    textViewCity.setText(cust.getCity());
    

提交回复
热议问题