Deepak
Deepak

Reputation: 1258

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.

Upvotes: 15

Views: 99959

Answers (8)

Yash
Yash

Reputation: 542

In MainActivity.class file You have to pass MainActivity context from MainActivity Class. Then in MyClass you have to Get MainActivity context. Remember Context and MyActivity are two different reference.

public class MyActivity extends Activity
{
    onCreate(){
        MyClass myobj=new MyClass(MyActivity context);    
    }
    public void Mymethod(){}
}

//HELPER CLASS IN A SEPARATE FILE

public class MyClass()
{
    MyActivity context;
    MyClass(MyActivity context)
    {
      this.context = context;

      this.context.Mymethod();
      //Or you can directly use activity context
      context.Mymethod();
    }
}

Upvotes: 0

Tmthetom
Tmthetom

Reputation: 79

You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Instance of AnotherClass for future use
    private AnotherClass anotherClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Create new instance of AnotherClass and
        // pass instance of MainActivity by "this"
        anotherClass = new AnotherClass(this);
    }

    // Method you want to call from another class
    public void myMethod(){
        ...
    }
}

AnotherClass.java

public class AnotherClass {

    // Main class instance
    private MainActivity mainActivity;  

    // Constructor
    public AnotherClass(MainActivity activity) {

        // Save instance of main class for future use
        mainActivity = activity;  

        // Call method in MainActivity
        mainActivity.myMethod();
    }
}

Upvotes: 2

pier shaw
pier shaw

Reputation: 101

This is probably the best way to do it. This is how I'm doing it. It's called a Singleton Design Pattern:

public class MyActivity extends Activity {
    private static MainActivity instance;

    public static MainActivity getInstance() {
     if(instance==null){
          setInstance(this);
        }
        return instance;
    }

    public static void setInstance(MainActivity instance) {
        MainActivity.instance = instance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setInstance(this);
    }
}

Upvotes: 10

neonDion
neonDion

Reputation: 2358

If I'm understanding you correctly I believe you can solve your problems using an interface as a callback.

////ACTIVITY/////////////////////////////////

 public class MyActivity() extends Activity {

    onCreate()
    {
        MyClass myObj=new MyClass();   

        //Set the listener on the object. Created as anonymous
        myObj.setListener(new MyClass.Listener() {
             myMethod();
        });
    }
}

public void myMethod(){

}

//////Custom Class//////////////////

public class MyClass {
     Listener mListener;

     public interface Listener {
          public void onInterestingEvent();
     }

     public void setListener(Listener listener) {
          mListener = listener;
     }

     public void someUsefulThingTheClassDoes() {
          //Do your code here and when you're ready to call the activity's method do this
          mListener.onInterestingEvent();
     }
}

Upvotes: 4

XtopherSD
XtopherSD

Reputation: 343

I had an inner class that I wanted to pull out into a more general library "Helper" class. I had the same issue you do. I got around it by making the helper class abstract, with a single abstract method. Then in my project package I extended the helper class with a constructor call in the specific class.

public class MyActivity extends Activity {
    onCreate() {
        MyHelperClass = new MyHelperClass(this, "foobar");
    }

    public void myMethod() {
        // Code...
    }
}

// In a different file
public class MyHelperClass extends HelperClass {
    private MyActivity mInstance;

    public MyHelperClass(MyActivity act, String data) {
        super();
        this.mInstance = act;
        this.mActivity = act;  // Useful for calling generic Activity methods in the HelperClass
        this.mData = data;
    }

    protected void callMyActivityMethod() {
        mInstance.myMethod();
    }
}

// In a different file
public abstract class HelperClass {
    protected Activity  mActivity;
    protected String    mData;

    public HelperClass() {
        // Subclass will set variables
    }

    protected abstract void callMyActivityMethod();

    // More code for all the other stuff the class does
}

In this way, I have a helper class that contains the vast majority of the "work", and all I have to do is make a subclass with the constructor and one method in order to get access to the calling activity's method of interest.

Upvotes: 3

Deepak
Deepak

Reputation: 1258

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();
    }

Upvotes: -12

blessanm86
blessanm86

Reputation: 31779

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();
    } 
} 

Upvotes: 28

Pratik
Pratik

Reputation: 30855

Make that method as static so you can call without creating the class object

public static void Mymethod()
{}

and call like this way

MainActivity.Mymethod();

Upvotes: 10

Related Questions