Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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.

like image 893
Deepak Avatar asked Oct 20 '11 13:10

Deepak


People also ask

How do you call a class 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 can call public method from another class 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.


Video Answer


1 Answers

Why not just pass the activity to the constructor like

public class MyActivity extends Activity { 

   onCreate(){ 
        MyClass myobj=new MyClass(MyActivity.this);     
   } 

   public void myMethod(){

   } 
} 

//HELPER CLASS IN A SEPARATE FILE     
public class MyClass{ 
    public MyClass(MyActivity act) { 
        act.myMethod();
    } 
} 
like image 138
blessanm86 Avatar answered Sep 20 '22 08:09

blessanm86