如何从一个活动(意图)向另一个活动发送数据?
我使用以下代码发送数据:
Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
首先,使用getIntent()
方法获取启动活动的意图:
Intent intent = getIntent();
如果多余的数据用字符串表示,则可以使用intent.getStringExtra(String name)
方法。在您的情况下:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
在接收活动中
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
// How to send value using intent from one class to another class
// class A(which will send data)
Intent theIntent = new Intent(this, B.class);
theIntent.putExtra("name", john);
startActivity(theIntent);
// How to get these values in another class
// Class B
Intent i= getIntent();
i.getStringExtra("name");
// if you log here i than you will get the value of i i.e. john