大家好,如果你愿意帮助我的话。我坚持如何从另一个活动中检索捆绑数据。基本上我有两个活动,就是当我按下第一个活动上的按钮时,它将继续第二个活动,然后设置稍后在第一个活动上传递的字符串值。我做的是我使用bundle来放置字符串值。我的问题是,如何从第二个活动中获取(字符串的)字符串值并将其返回到第一个活动?这是我的代码:
FirstActivity(继续第二项活动):
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;
}
}
答案 0 :(得分:3)
您需要执行以下操作:
@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
同样在 SecondActivity 中,您需要使用新的意图:
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);
}
});
}