How to get back the result from Child activity to Parent in android?

前端 未结 2 789
北海茫月
北海茫月 2020-12-28 22:05

I\'am starting a child activity on click of a button from Parent. And i\'am calculating some result (of type string) in child activity and finishing the child to come back t

相关标签:
2条回答
  • 2020-12-28 22:37

    In Parent Activity

    Intent intent = new Intent(getApplicationContext(), yourChildActivity.class);
    intent.putExtra("key", "value");
    startActivityForResult(intent, ACTIVITY_CONSTANT);
    

    in child activity to sent back result of your parent activity through

    Intent data = new Intent();
    data.putExtra("key1", "value1");
    data.putExtra("key2", "value2");
    // Activity finished return ok, return the data
    setResult(RESULT_OK, data);
    finish();
    

    and get child activity result information in your parent activity

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            if (data.hasExtra("key1") && data.hasExtra("key2")) {
                Toast.makeText(
                    this,
                    "Your reult is :  "data.getExtras().getString("key1") + " " + data.getExtras().getString("key2"),
                    Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-28 22:44

    Instead of startActivityForResult(new Intent(ParentActivity.this, ChildActivity.class), ACTIVITY_CONSTANT);

    You can use putExtras() method to pass values between activities:

    In Child Activity:

    Intent data = new Intent();
    data.putExtra("myData1", "Data 1 value");
    data.putExtra("myData2", "Data 2 value");
    // Activity finished ok, return the data
    setResult(RESULT_OK, data);
    finish();
    

    And in Parent activity, you can override onActivityResult() and inside that you can have Intent paramater and from the Intent parameter of this method you can retrieve the extra values passed from the child activity, such as intent.getStringExtra or intent.getSerializableExtra.

    for example:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            if (data.hasExtra("myData1")) {
                Toast.makeText(this, data.getExtras().getString("myData1"),
                    Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题