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

后端 未结 30 3692
-上瘾入骨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:08

    Your class should implements Serializable or Parcelable.

    public class MY_CLASS implements Serializable
    

    Once done you can send an object on putExtra

    intent.putExtra("KEY", MY_CLASS_instance);
    
    startActivity(intent);
    

    To get extras you only have to do

    Intent intent = getIntent();
    MY_CLASS class = (MY_CLASS) intent.getExtras().getSerializable("KEY");
    

    If your class implements Parcelable use next

    MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");
    

    I hope it helps :D

提交回复
热议问题