Home » Android » android – how to call method in activity form non activity class

android – how to call method in activity form non activity class

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have an Activity and non Activity class. How to call a method in Activity class from non Activity class

public class MainActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        DataClass dc = new DataClass();
        dc.show();                  
    }

    public void call(ArrayList<String> arr) {
       // Some code...
    }
}

public class DataClass {

    public void show(ArrayList<String> array) {
        // Here I want to send this ArrayList values into the call
        // method in activity class.

       MainActivity act = new MainActivity();
       act.call(array);                  
    }
}
How to&Answers:

Just create a callback interface inside the DateClass.

public DateClass {
    public interface IDateCallback {
        void call(ArrayList<String> arr);
    }  

    private IDateCallback callerActivity;

    public DateClass(Activity activity) {  
        callerActivity = (IDateCallback)activity;  
    }
...  
}  

public void show(ArrayList<String> array) {            
    callerActivity.Call(array);  
    ...  
}

//And implements it inside your activity.

public class MainActivity extends Activity 
        implements IDateCallback {  

    public void call(ArrayList<String> arr) {

    }  
}

Answer:

Well there are several things you could do. I think the easiest for you would be to send the Context into DataClass like so:

DataClass dc =new DataClass();
dc.show(this);

And in your DataClass save the context into a global var Context context. Then use it like so:

((MainActivity)context).call(array);

Answer:

((MainActivity)getContext).array();

Answer:

Just make a singleton like:

TeacherDashboardSingleton:

public class TeacherDashboardSingleton {
public  Teacher_Dashboard aa;
private static final TeacherDashboardSingleton ourInstance = new TeacherDashboardSingleton();
   public static TeacherDashboardSingleton getInstance() {
        return ourInstance;
    }
}

myActivity class:

onCreate(....){
 ....
   TeacherDashboardSingleton.getInstance().aa = this;
....
}

this will create an object of same instance as in activity

now you can use it from anywhere