Search code examples
androidonactivityresult

onActivityResult not being called when going back


I am trying to pass data backwards to an activity, however I can never get my onActivityResult function to be called. When I start the new activity, I create a new intent like regular

 Intent intent = new Intent(this, NewLoanCost.class);

 intent.putExtra("defaultsArray", jDefaultsArray.toString());
 intent.putExtra("loanSelection", loanSelection);
 intent.putExtra("buyerSellerSelection", buyerSellerSelection);

 startActivity(intent);

and when I want to go back to the previous activity, I am overriding the back button to create a new intent and store the data

@Override
public void onBackPressed() {
    Intent intent = new Intent();

    intent.putExtra("fullCosts", fullCosts.toString());

    setResult(RESULT_OK, intent);

    super.onBackPressed();
}

but in the first activity, I can't even get a debugging toast to appear. Am I missing something blatant?

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    Toast.makeText(this, "onActivityResult", Toast.LENGTH_SHORT).show();
    if (requestCode == 1) {
        if(resultCode == RESULT_OK){
            try {
                jDefaultsArray = new JSONArray(data.getStringExtra("fullCosts"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Solution

  • To receive a result you should use startActivityForResult instead of startActivity