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

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

    First implement Parcelable in your class. Then pass object like this.

    SendActivity.java

    ObjectA obj = new ObjectA();
    
    // Set values etc.
    
    Intent i = new Intent(this, MyActivity.class);
    i.putExtra("com.package.ObjectA", obj);
    
    startActivity(i);
    

    ReceiveActivity.java

    Bundle b = getIntent().getExtras();
    ObjectA obj = b.getParcelable("com.package.ObjectA");
    

    The package string isn't necessary, just the string needs to be the same in both Activities

    REFERENCE

提交回复
热议问题