0
votes

I have two Activites and I start an Intent on the Second Activity to retrieve a result using startActivityForResult(...), and then handeling the result with onActivityResult(...).

Problem is the resultCode that is returned from the Second Activity is always RESULT_CANCELED. Thus not getting past the conditional "resultCode == RESULT_OK", to update the textView in my Main Acitivty.

Main activity

@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);
        }
    }
}

Second Activity

@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
@MartinZeitler textView.setText("Resultcode "+resultCode); In the onActivityResult always results in Resultcode 0. 0 means RESULT_CANCELED - user4641064

1 Answers

0
votes

try to use the intent passed instead of creating a new one:

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

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

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

there is nothing else which would look wrongful.