Search code examples
androidandroid-activity

Can I create an object of an Activity in other class?


I have defined a function in MainActivity now I want to access the function from another class in my app. I have created an object of the MainActivity and with that object I have called the function. Although there is no error, it's not executing. Every time I try to execute, the app crashes.


Solution

  • Activity A should have a variable

    static ActivityA activityA;
    

    In onCreate state:

    activityA = this;
    

    and add this method:

    public static ActivityA getInstance(){
       return   activityA;
     }
    

    In activity B, call

    ActivityA.getInstance().myFunction(); //call myFunction using activityA