Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method in MainActivity from another class?

Tags:

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?

like image 838
shannon Avatar asked Jun 26 '13 09:06

shannon


People also ask

How do you call a method from another class?

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.

How do you call a method from one class to another in Android?

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.

How do you call a method in Android Studio?

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.


1 Answers

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!

like image 122
RicardoSousaDev Avatar answered Sep 29 '22 17:09

RicardoSousaDev