Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call method in activity form non activity class

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);                  
    }
}
like image 813
user2932841 Avatar asked Oct 29 '13 15:10

user2932841


People also ask

How can we call method in activity from non activity class?

onCreate(savedInstanceState); setContentView(R. layout. main2); DataClass dc = new DataClass(); dc. show(); } public void call(ArrayList<String> arr) { // Some code... } }

How do you create an instance of an activity?

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.


2 Answers

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);
like image 163
Andy Avatar answered Oct 24 '22 09:10

Andy


((MainActivity)getContext).array();
like image 45
Farzam Menbary Avatar answered Oct 24 '22 11:10

Farzam Menbary