Here is my first activity
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
public void addNumbers() {
////
}
}
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// I need to call addNumbers() from here
}
I have tried instantiating FirstActivity in SecondActivity like so but I get an error. And I also heard its not the best practice to instantiate the whole activity.
FirstActivity firstActivity = new FirstActivity();
firstActivity.addNumbers();
3
Answers
Instead of calling method in second activity, create a separate public class e.g.
Functions.java
, and implement it asNow in your second activity where you want to call the method
Add the static keyword to your shared methods
Then use:
For more details check out this answer
It is better to put the mathematical operations in a repository and, if necessary, find the instance of that repository each time by calling its instance.
You can use these codes.
First Make this Repository
Second Call Method
Now you can easily use other methods inside by calling this class