How to send an object from one Android Activity to another using Intents?

后端 未结 30 3585
-上瘾入骨i
-上瘾入骨i 2020-11-21 04:47

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?

30条回答
  •  执笔经年
    2020-11-21 05:32

    implement serializable in your class

    public class Place implements Serializable{
            private int id;
            private String name;
    
            public void setId(int id) {
               this.id = id;
            }
            public int getId() {
               return id;
            }
            public String getName() {
               return name;
            }
    
            public void setName(String name) {
               this.name = name;
            }
    }
    

    Then you can pass this object in intent

         Intent intent = new Intent(this, SecondAct.class);
         intent.putExtra("PLACE", Place);
         startActivity(intent);
    

    int the second activity you can get data like this

         Place place= (Place) getIntent().getSerializableExtra("PLACE");
    

    But when the data become large,this method will be slow.

提交回复
热议问题