如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
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 id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
其他回答
如果您试图获取碎片中的额外数据,则可以尝试使用:
放置数据时使用:
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);
使用以下方法获取数据:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getArguments().getInt(ARG_SECTION_NUMBER);
getArguments().getString(ARG_SECTION_STRING);
getArguments().getBoolean(ARG_SECTION_BOOL);
getArguments().getChar(ARG_SECTION_CHAR);
getArguments().getByte(ARG_SECTION_DATA);
}
您可以从intent中获取任何类型的额外数据,无论是对象、字符串还是任何类型的数据。
Bundle extra = getIntent().getExtras();
if (extra != null){
String str1 = (String) extra.get("obj"); // get a object
String str2 = extra.getString("string"); //get a string
}
最短的解决方案是:
Boolean isGranted = getIntent().getBooleanExtra("tag", false);
// 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
不要初始化另一个新的Intent来接收数据,只需执行以下操作:
String id = getIntent().getStringExtra("id");
在接收活动中
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}