Deepak Deepak - 3 months ago 20
Android Question

Call a public method in the Activity class from another class?

MAIN ACTIVITY

public class MyActivity() extends Activity
{
onCreate()
{
MyClass myobj=new MyClass();
}
public void Mymethod()
{}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass()
{
MyClass(Context context)
{

}
}


I tried to call Mymethod() from an instance of MyClass.
I would really appreciate any help. Thanks.

Answer

I decided to write the HelperClass MyClass as an inner class of MyActivity class. This allows it full access to parent class but the bad thing is now MyClass is restricted to MyActivity class only.

public class MyActivity() extends Activity
{
    onCreate()
    { 
        MyClass myobj=new MyClass();

    } 

    public void myMethod()
    {

    } 
} 
//INNER CLASS
    public class MyClass
    { 
        public MyClass() 
        { 

        } 
        //I can directly access the MyMethod
        myMethod();
    }
Comments