Can i Create the object of a activity in other class?

i have defined a function in mainactivity now i want to access with another class in my app.I have created a object of the mainactivity by using that object i have called the function.It is not showing any error but its not executing every time i try to execute the app crashes? any solutions


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

You cannot just create objects of Activities by using:

MyActivity activity = new MyActivity();

as you would with normal Java classes. All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them.

By treating an Activity as a normal Java class, you end up with a null context. As most methods in an Activity are called on its Context, you will get a null pointer exception, which is why your app crashes.

Instead, move all such methods which need to be called from other classes into a Utility class which accepts a valid context in its constructor, and then use that context in the methods to do the work.