Search code examples
androidandroid-activity

how to call a method(in activity(A)) from another activity(B) to work on that activity(A)?


I have 2 activity. one is main activity("A") and another is a Dialog("B") and it("B") is also an activity. when I click "ok" on dialog("B") it("B") will be closed and a method will be called in activity "A" and the method will work on activity("A"). How can I call a method from activity("B") to work on activity("A)?? I am learning android studio and don't know much.


Solution

  • You want to call a method which is in Activity A from Activity B. First of all, the interactivity communications are not advisable the way you have portrayed it.

    But, there are ways you can achieve what you have asked.

    1. Start Activity For Result

    If the Activity B is started from Activity A using StartActityForResult,

     //Activity A
    
     val intent = Intent(this, ActivityB::class.java)
     startActivityForResult(intent, 1001) //Any request code
    

    You can get the result in onActivityResult callback on activity A.

    override fun onActivityResult(requestCode: Int, resultCode: Int, data:Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1001 && resultCode == Activity.RESULT_OK)
            callYourMethod()
    }
    
    1. Pass a boolean in the intent. (This is kind of a hack)

    When you click ok on the dialog in Activity B, call activity A by passing a boolean value in the intent.

     val intent = (this, ActivityA::class.java)
     val bundle = Bundle()
     bundle.putBoolean("KEY", true)
     startActivity(intent, bundle)
    

    And in Activity A's onCreate method, get the bundle from intent, and if it is true, then call the method.

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            val isTrue = intent.getBooleanExtra("KEY", false) //false is default value
            if(isTrue) 
              callYourMethod()
        }
    

    There's also another way to communicate between classes like from adapter to Activity, fragment to activity etcetera using Interface. But, I hope the above-mentioned steps will help you for now.