How do I call the method startChronometer
in another class when the method is declared inside the main activity?
Inside MainActivity
:
public void startChronometer() {
mChronometer.start();
showElapsedTime();
}
Inside another class, I tried to do this:
MainActivity mActivity;
mActivity.startChronometer();
But an error occurred which said:
java.lang.NullPointerException.
May I know what more I need to add to the code?
In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.
You should use the following code : Class2 cls2 = new Class2(); cls2. UpdateEmployee(); In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.
To call a method in Java, you type the method's name, followed by brackets. This code simply prints “Hello world!” to the screen. Therefore, any time we write helloMethod(); in our code, it will show that message to the screen.
You can easily call a method from any Fragment inside your Activity by doing a cast like this:
Java
((MainActivity)getActivity()).startChronometer();
Kotlin
(activity as MainActivity).startChronometer()
Just remember to make sure this Fragment's activity is in fact MainActivity before you do it.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With