Use onactivityresult android

android

Solution

Define constant

public static final int REQUEST_CODE = 1;

Call your custom dialog activity using intent

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

Now use onActivityResult to retrieve the result

@Override
    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(),
                    Toast.LENGTH_SHORT).show();
        }

    }

In custom dialog activity use this code to set result

Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();

Problem

I want to call a method from `mainactivity` in other activities. For that, I've researched a lot and found that using `OnActivityResult` 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. Thanks! 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.

Original source