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

后端 未结 30 4142
遇见更好的自我
遇见更好的自我 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:45

    Above answers almost all correct but for those who doesn't undestand those answers Android has powerfull class Intent with help of it you share data between not only activity but another components of Android (broadcasr receiver, servises for content provide we use ContetnResolver class no Intent). In your activity you build intent

    Intent intent = new Intent(context,SomeActivity.class);
    intent.putExtra("key",value);
    startActivity(intent);
    

    In your receving activity you have

    public class SomeActivity extends AppCompactActivity {
    
        public void onCreate(...){
        ...
              SomeObject someObject = getIntent().getExtras().getParceable("key");
        }
    
    }
    

    You have to implement Parceable or Serializable interface on your object in order to share between activities. It is hard to implement Parcealbe rather than Serializable interface on object that's why android has plugin especially for this.Download it and use it

提交回复
热议问题