如何将数据从一个活动(意图)发送到另一个活动?
我使用此代码发送数据:
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);
当前回答
在接收活动中
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
其他回答
你也可以这样做//将价值放在意图上
Intent in = new Intent(MainActivity.this, Booked.class);
in.putExtra("filter", "Booked");
startActivity(in);
//从意图中获得价值
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String filter = bundle.getString("filter");
科特林
第一项活动
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
第二项活动
val value = getIntent().getStringExtra("key")
建议
始终将密钥放在常量文件中,以便于管理。
companion object {
val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}
// 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 intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);
按意图获取数据:
String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);
如果我们对意图使用整数值,则必须在getIntent().getIntExtra(“instituteId”,0)中将第二个参数设置为0。否则,我们不使用0,Android会给我一个错误。
这是针对适配器的,对于您只需要更改mContext的活动对于片段,您需要将mContext更改为获取活动()
public static ArrayList<String> tags_array ;// static array list if you want to pass array data
public void sendDataBundle(){
tags_array = new ArrayList();
tags_array.add("hashtag");//few array data
tags_array.add("selling");
tags_array.add("cityname");
tags_array.add("more");
tags_array.add("mobile");
tags_array.add("android");
tags_array.add("dress");
Intent su = new Intent(mContext, ViewItemActivity.class);
Bundle bun1 = new Bundle();
bun1.putString("product_title","My Product Titile");
bun1.putString("product_description", "My Product Discription");
bun1.putString("category", "Product Category");
bun1.putStringArrayList("hashtag", tags_array);//to pass array list
su.putExtras(bun1);
mContext.startActivity(su);
}