Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...