Search code examples
android-fragmentsandroid-activity

Call fragment method inside an activity from another activity


I have an Activity A with a Fragment and an Activity B.

When I click a button inside the Fragment, the Activity B is starting and i assume that the Activity A is onPause.

What I want to do is to click on a button inside the Activity B which will finish() this Activity and then go back to the Activity A.

Doing so would automatically call a method inside the fragment. After research I tried to implements Interface and Fragment transactions but I always get null objects.

How can I make my activities communicating and pass the information to the fragment in this configuration?


Solution

  • Call ActivityB from FragmentA (which is part of ActivityA) as startActivityForResult() instead of startActivity() call.

    Using this, you would be able to pass back result from Activity B to Fragment A.

    Fragment A (Part of ActivityA) :

    // Calling Activity B
    Intent intent = new Intent(this, ActivityB.class); 
    intent.putExtras(b);    
    startActivityForResult(intent, ANY_ID);
    
    // Overriding callback for result
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == ANY_ID && resultCode == Activity.RESULT_OK) {
            // Your logic of receiving data from Activity B
        }
    }
    

    Important Point : The Fragment A is the one making the startActivityForResult() call, but it is part of Activity A so Activity A gets the first shot at handling the result. It has to call super.onActivityResult() so that the callback can come to Fragment A

    In Activity A :

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // This is required, in order to get onActivityResult callback in Fragment A
    }
    

    Setting result back from Activity B :

    Intent resultIntent = new Intent();
    // You can pass any data via this intent's bundle by putting as key-value pair
    resultIntent.putExtra("Key", Value);
    setResult(Activity.RESULT_OK, resultIntent);
    finish();
    

    Reference :

    1. https://stackoverflow.com/a/22554156/1994950
    2. https://stackoverflow.com/a/6147919/1994950
    3. Start Activity for result