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

后端 未结 30 3963
遇见更好的自我
遇见更好的自我 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条回答
  •  执念已碎
    2020-11-21 04:50

    Implement your class with Serializable. Let's suppose that this is your entity class:

    import java.io.Serializable;
    
    @SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
    public class Deneme implements Serializable {
    
        public Deneme(double id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public double getId() {
            return id;
        }
    
        public void setId(double id) {
            this.id = id;
        }
    
        public String getName() {
            return this.name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        private double id;
        private String name;
    }
    

    We are sending the object called dene from X activity to Y activity. Somewhere in X activity;

    Deneme dene = new Deneme(4,"Mustafa");
    Intent i = new Intent(this, Y.class);
    i.putExtra("sampleObject", dene);
    startActivity(i);
    

    In Y activity we are getting the object.

    Intent i = getIntent();
    Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");
    

    That's it.

提交回复
热议问题