startActivityForResult()返回结果代码RESULT_CANCELED

时间:2018-11-17 18:30:20

标签: android

我有两个Activite,我在Second Activity上启动了一个Intent,以使用startActivityForResult(...)检索结果,然后使用onActivityResult(...)处理结果。

问题是从第二个活动返回的resultCode始终为RESULT_CANCELED。这样就不会超过条件“ resultCode == RESULT_OK”来更新我的主要活动中的textView。

主要活动

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Intent chooseIntent = new Intent(this,ChooseActivity.class);
    Button startIntent = findViewById(R.id.button);

    startIntent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivityForResult(chooseIntent,1);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    TextView textView = findViewById(R.id.choiceResultView);
    if (requestCode == 1) {
        textView.setText("Resultcode "+resultCode);
        if (resultCode == RESULT_OK) {
            String returnedResult = data.getStringExtra("choice");
            textView.setText(returnedResult);
        }
    }
}

第二活动

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choose);

    Button lockChoice = findViewById(R.id.choose);
    RadioGroup selection = findViewById(R.id.selection);
    final RadioButton selected = (RadioButton) findViewById(selection.getCheckedRadioButtonId());

    lockChoice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent choice = new Intent();
            choice.putExtra("choice",selected.toString());
            setResult(RESULT_OK,choice);
            finish();
        }
    });

}

1 个答案:

答案 0 :(得分:0)

尝试使用传递的意图,而不是创建新意图:

Bundle extras = new Bundle();
extras.putString("choice", selected.toString());

Intent intent = getActivity().getIntent();
intent.putExtras(extras);

getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();

没有其他东西看起来不对劲了。