How to call a method in the form of activity non activity class

I have an Activity class and non Activity. How to call a method in the Activity class from the 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); } } 
+7
android android-activity
source share
4 answers

Just create a callback interface inside 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) { } } 
+13
source share

Well, there are a few things you could do. I think it’s easiest for you to send Context to a DataClass like this:

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

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

 ((MainActivity)context).call(array); 
+6
source share
 ((MainActivity)getContext).array(); 
+1
source share

Just create a singleton, for example:

TeacherDashboardSingleton:

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

class myActivity:

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

this will create an object of the same instance as in action

now you can use it from anywhere

0
source share

All Articles