Chinmay Dabke
Chinmay Dabke

Reputation: 5140

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.

Upvotes: 34

Views: 97030

Answers (4)

Kuldeep Rathod
Kuldeep Rathod

Reputation: 1

 if (requestCode == 2000)
    {
        if (resultCode == Activity.RESULT_OK)
        {
            try {

                Uri selectedImages = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getActivity().getContentResolver().query(selectedImages,
                        filePathColumn,null,null,null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

                receivedImageBitmap = BitmapFactory.decodeFile(picturePath);
                imageView.setImageBitmap(receivedImageBitmap);

            }
            catch (Exception e)
            {
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

Upvotes: -1

Sonu Singh Bhati
Sonu Singh Bhati

Reputation: 1073

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();

Upvotes: 95

Md. Zakir Hossain
Md. Zakir Hossain

Reputation: 1092

Start the Activity:

you do need to pass an additional integer argument to the startActivityForResult() method.You may do it by defining a constant or simply put an integer.The integer argument is a "request code" that identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.

static final int ASK_QUESTION_REQUEST = 1;
// Create an Intent to start SecondActivity
Intent askIntent = new Intent(FirstActivity.this, SecondActivity.class);

// Start SecondActivity with the request code
startActivityForResult(askIntent, ASK_QUESTION_REQUEST);

Return The Result:

After completing your work in second activity class simply set the result and call that activity where it comes from and lastly don't forget to write finish() statement.

// Add the required data to be returned to the FirstActivity
            sendIntent.putExtra(Result_DATA, "Your Data");

            // Set the resultCode to Activity.RESULT_OK to
            // indicate a success and attach the Intent
            // which contains our result data
            setResult(RESULT_OK, sendIntent);

            // With finish() we close the SecondActivity to
            // return to FirstActivity
            finish();

Receive The Result:

When you done with the subsequent activity and returns, the system calls your activity's onActivityResult() method. This method includes three arguments:

@The request code you passed to startActivityForResult(). @A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the operation failed @An Intent that carries the result data.

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

    // check if the request code is same as what is passed  here it is 1
    if (requestCode == ASK_QUESTION_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            final String result = data.getStringExtra(SecondActivity.Result_DATA);

            // Use the data - in this case display it in a Toast.
            Toast.makeText(this, "Result: " + result, Toast.LENGTH_LONG).show();
        }
    }
}

Upvotes: 7

Aung Htet Kyaw
Aung Htet Kyaw

Reputation: 11

This is my example.

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

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Image_Request_Code && resultCode ==RESULT_OK && data != null && data.getData() != null) {

            FilePathUri = data.getData();

            try {

                // Getting selected image into Bitmap.
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);

                // Setting up bitmap selected image into ImageView.
                SelectImage.setImageBitmap(bitmap);

                // After selecting image change choose button above text.
                ChooseButton.setText("Image Selected");

            }
            catch (IOException e) {

                e.printStackTrace();
            }
        }*strong text*

Upvotes: 1

Related Questions