简体   繁体   中英

Use onActivityResult to call a function

I have an PopUpActivity which pops up a window and i'm very satisfied with that.

However, I want to be able to return information from the popup window back to the parent activity, but also be able to call a function on the parent activity once the popup window is closed. Could someone help me?

Here is my code in the PopUpActivity :

public void closePopUpAndSendResultBack(){ // and how can i pass data to the previous activity?
    //https://developer.android.com/training/basics/intents/result
    Intent data = new Intent();
    data.putExtra("data", "yo");
    //startActivityForResult(data, 1);  // gives me the error : android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
    setResult(Activity.RESULT_OK, data);
    finish();

}

and here is my parent(MainActivity) function that I want to get called once the popUpWindow is closed:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {

            nameTextField.setText(""); // how can i get Yo inside here?
            showTheButton(); // and how can this function get called?

        }

    }
}}

Also, here is how I make that window Pop up from my Mainactivity:

     theOkButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
            pop_up_that_window.putExtra("first", "Velkommen du der!");
            startActivity(pop_up_that_window);

        }
    });


 }

Could someone help me please?

In MainActivity use:

theOkButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
        pop_up_that_window.putExtra("first", "Velkommen du der!");
        MainActivity.this.startActivityForResult(pop_up_that_window, 1);

    }
});

And still in MainActivity in onActivityResult() use this code:

String yo = data.getStringExtra("data")
nameTextField.setText(yo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM