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.
2 Answers
You can use the command pattern here. You can create an interface in your ActivityB
Eg:
public interface OnYourButtonClickListener
{
void performActionOnClick(Params...);
}
Now, Make your ActivityA
implement the above interface and override the method in the interface in your ActivityA
, i.e. override performActionOnClick
.
Now, Make sure to receive the context of the calling activity (where you have implemented the interface) in your ActivityB
and cast it to your interface type so that you can call the action which you want to perform.
To read more about this pattern: https://en.wikipedia.org/wiki/Command_pattern

- 7,179
- 4
- 43
- 57
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.
- 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()
}
- 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.

- 453
- 1
- 4
- 14