Chinmay Dabke Chinmay Dabke - 1 month ago 16
Android Question

Use onactivityresult android

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.

Answer

Define constant

public static final 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();
Comments