Sending data back to the Main Activity in Android

后端 未结 12 1957
后悔当初
后悔当初 2020-11-22 01:36

I have two activities: main activity and child activity.
When I press a button in the main activity, the child activity is launched.

Now I want to send some dat

12条回答
  •  心在旅途
    2020-11-22 02:11

    Activity 1 uses startActivityForResult:

    startActivityForResult(ActivityTwo, ActivityTwoRequestCode);
    

    Activity 2 is launched and you can perform the operation, to close the Activity do this:

    Intent output = new Intent();
    output.putExtra(ActivityOne.Number1Code, num1);
    output.putExtra(ActivityOne.Number2Code, num2);
    setResult(RESULT_OK, output);
    finish();
    

    Activity 1 - returning from the previous activity will call onActivityResult:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ActivityTwoRequestCode && resultCode == RESULT_OK && data != null) {
            num1 = data.getIntExtra(Number1Code);
            num2 = data.getIntExtra(Number2Code);
        }
    }
    

    UPDATE: Answer to Seenu69's comment, In activity two,

    int result = Integer.parse(EditText1.getText().toString()) 
               + Integer.parse(EditText2.getText().toString());
    output.putExtra(ActivityOne.KEY_RESULT, result);
    

    Then in activity one,

    int result = data.getExtra(KEY_RESULT);
    

提交回复
热议问题