Android使用捆绑从另一个活动中检索onActivityResult上的结果 [英] Android retrieving result on onActivityResult from another activity using bundle
问题描述
大家好,如果您能帮助我的话.我被困在如何从另一个活动中检索捆绑数据的问题.基本上,我有两个活动,即当我在第一个活动上按下按钮时,它将继续在第二个活动上,然后设置字符串值,该字符串值稍后将传递给第一个活动.我所做的是我使用捆绑软件放置了字符串值.我的问题是,如何从第二个活动中获取(字符串的)捆绑值并将其返回到第一个活动中?这是我的代码:
Hello everyone if you would kindly help me. I'm stuck on how to retrieve the bundle data from another activity. Basically I have two activities which is that when I pressed a button on the first activity, it will go on the second activity and then sets the string values which is later on to be passed on the first activity. What I did was I used the bundle to put the string values. My question is that how can I get the bundle values (of strings) from the second activity and return it on to the first activity? Here is my code:
第一个活动(正在进行第二个活动):
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(this,
SecondActivity.class), REQUEST_CODE_SAMPLE);
}
});
SecondActivity :(返回捆绑商品的价值)
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle b = new Bundle();
bundle.putString("A", "Aloha");
bundle.putString("B", "Bubbles");
setResult(
Activity.RESULT_OK,
getIntent().putExtras(b));
}
});
}
FirstActivity(用于检索捆绑商品值):
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SAMPLE:
if (resultCode == RESULT_OK) {
bundle = getIntent().getExtras();
//WHAT TO DO TO GET THE BUNDLE VALUES//
String a = //STORE FIRST VALUE OF BUNDLE
String b = //STORE SECOND VALUE OF BUNDLE
}
break;
default:
break;
}
}
推荐答案
您需要执行以下操作:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SAMPLE:
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
//WHAT TO DO TO GET THE BUNDLE VALUES//
String a = bundle.getString("A");
String b = bundle.getString("B");
}
break;
}
}
但请注意,您必须使用传递给onActivityResult
而不是getIntent
but take care, you must use the intent passed to the onActivityResult
not getIntent
还需要在 SecondActivity 中使用新的意图:
Also in SecondActivity, you need to use a new intent:
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle= new Bundle();
bundle.putString("A", "Aloha");
bundle.putString("B", "Bubbles");
Intent returnIntent = new Intent();
returnIntent.putExtras(bundle);
setResult(Activity.RESULT_OK, returnIntent);
}
});
}
这篇关于Android使用捆绑从另一个活动中检索onActivityResult上的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!