How can I call a function defined in class#A from class#B? Class#B extends AsynchTask and fetches remote data from a web service. The class#A function I am attempting to call from class#B is used to send the retrieved remote data for Class#A to display.
I am trying to pass the current instance of class#A to class#B using this
but that just passes the context so the functions are not recognized.
I also tried using static
but as the function runs a new thread, defining the function as static generates a compiler error.
The code I am trying to call is as follows:
public void test(List<DATA> Data){
this.Data = Data;
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for(DATA data : MainActivity.this.Data){
Toast.makeText(MainActivity.this, data.title, Toast.LENGTH_SHORT).show();
}
}
});
}
This is how you would do it:
In MainActivity:
ClassBAsyncTask mat = new ClassBAsyncTask(this, .., ..);
ClassBAsyncTask's contructor:
public ClassBAsyncTask(MainActivity context, .., ..) {
mContext = context;
....
....
}
To call MainActivity's method test(List<DATA>)
from within ClassBAsyncTask
:
((MainActivity)mContext).test(yourListVariable);
Look into weak references to make sure that the AsyncTask
does not use mContext
when the activity no longer exists.