我在StackOverflow和Google上阅读了许多类似的问题,但它们都没有帮助我解决我的问题。我有两个活动,A和B。A通过一个活动来请求B的结果:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnuMainSettings:
startActivity(new Intent(ActivityMain.this, ActivitySettings.class));
break;
case R.id.mnuMainHelp:
startActivity(new Intent(ActivityMain.this, ActivityHelp.class));
break;
case R.id.mnuMainEULA:
Intent intent = new Intent(ActivityMain.this, ActivityDisclaimer.class);
startActivityForResult(intent, 1);
break;
}
return true;
}
活动 B:
public class ActivityDisclaimer extends Activity
{
private WebView webView;
public static final int ACTIVITY_RESULT_DISCLAIMER = 1;
public static final String ACTIVITY_RESULT = "result";
public static final int ACTIVITY_RESULT_OK = 1;
public static final int ACTIVITY_RESULT_CANCELED = 2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.disclaimer);
webView = (WebView) findViewById(R.id.WebViewDisclaimer);
webView.loadUrl("file:///android_asset/disclaimer.html");
}
public void onClickDisclaimerBtnAccept(View view) {
Prefs prefs = new Prefs(this);
prefs.setAcceptDisclaimer(true);
prefs.commit();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",true);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
public void onClickDisclaimerBtnDecline(View view) {
Prefs prefs = new Prefs(this);
prefs.setAcceptDisclaimer(false);
prefs.commit();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",false);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
}
然而,我的onActivityResult方法中返回的数据总是NULL。
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// For response from disclaimer activity
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK){
if (null != intent) {
Boolean accepted = intent.getBooleanExtra("result", false);
Log.d(TAG, "Boolean Data: " + accepted.toString());
if (!accepted) finish();
} else { Log.d(TAG, "RESULT OK, DATA NULL"); }
}
if (resultCode == Activity.RESULT_CANCELED){
if (null != intent) {
Boolean accepted = intent.getBooleanExtra("result", false);
Log.d(TAG, "Boolean Data: " + accepted.toString());
finish();
} else { Log.d(TAG, "RESULT CANCELED, DATA NULL"); }
}
}
}//onActivityResult
“RESULT CANCELED,DATA NULL”是我一直收到的信息。我错过了什么吗?也许我已经盯着这段代码看太久了!
编辑:更具体地说,为什么我会得到一个空返回值?
intent!= null
而不是null!= intent
吗? 此外,在Activity B中的setResult
中,只需放置RESULT_OK
而不需要Activity。 - gilonmACTIVITY_RESULT_OK
,但在activity中你使用了Activity.RESULT_OK
) - gilonm