Chinmay Dabke Chinmay Dabke - 1 year ago 113
Android Question

Use onactivityresult android

I want to call a method from

in other activities. For that, I've researched a lot and found that using
is the best option. Can anyone please explain how to use this method with the help of an example? I've gone through similar questions but found them confusing.

EDIT:I have a custom dialog activity in my app. It asks the users whether they want to start a new game or not and it has two buttons yes and no. I want to implement the above method only to get the pressed button.

Answer Source

Define constant

public static final REQUEST_CODE = 1;

Call your custom dialog activity using intent

Intent intent = new Intent(Activity.this,
            startActivityForResult(intent , REQUEST_CODE);

Now use onActivityResult to retrieve the result

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == REQUEST_CODE  && resultCode  == RESULT_OK) {

                String requiredValue = data.getStringExtra("Key");
        } catch (Exception ex) {
            Toast.makeText(Activity.this, ex.toString(),


In custom dialog activity use this code to set result

Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download