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);
}
}
onCreate(savedInstanceState); setContentView(R. layout. main2); DataClass dc = new DataClass(); dc. show(); } public void call(ArrayList<String> arr) { // Some code... } }
Activity instances are always created by the Android system. This is because a lot of initializations have to be done for the activity to work. To create a new activity you call startActivity with an Intent describing the activity to start.
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);
((MainActivity)getContext).array();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With