Reputation: 111
I tried to call the "AsyncTask" class from another class called "MainActivity" but "AsyncTask" Class is inside the class called "SiteAdapter". I tried to pass a reference but it not working. How could do that?
Main Activity:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Call the class AsyncTask
new GetAddressTask(this).execute(); // <----ERROR - GetAddressTask cannot be resolved to a type
}
}
AsyncTask inside SitesAdapter class:
public class SitesAdapter extends ArrayAdapter<StackSite> {
...//PROCESS
public class GetAddressTask extends AsyncTask<String, Void, String> {
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
//Pass a reference to MainActivity
private MainActivity mainActivity; // <--- WARNING - The value of the field SitesAdapter.GetAddressTask.mainActivity is not used
public GetAddressTask(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
}
@Override
protected String doInBackground(String... arg0) {
...
}
@Override
protected void onPostExecute(String result) {
...
}
}
}
Upvotes: 3
Views: 7124
Reputation: 2969
First of all, MainActivity
is not a class that you can not define an object from. It extends Activity
.
Change your AsyncTask
class with it;
public static class GetAddressTask extends AsyncTask<String, Void, String> {
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
@Override
protected String doInBackground(String... values) {
// If you want to use 'values' string in here
String values = values[0];
}
@Override
protected void onPostExecute(String result) {
...
}
}
Then call this with it;
String values = ""; //You can pass any string value to GetAddressTask with that parameter
//Call the class AsyncTask
new SitesAdapter.GetAddressTask(this).execute(values);
Upvotes: 4
Reputation: 406
Try this, this is working for me.
Just create a method in your SitesAdapter
class and call it from your MainActivity
like this :
new SitesAdapter().start(MainActivity.this);
now in your SitesAdapter
class do this :
private Context mContext;
public void start(){
mContext = context;
new GetAddressTask().execute();
}
May this help you
Upvotes: 2
Reputation: 44571
You could make it static
then call it with
SitesAdapter.GetAddressTask myClass = new SitesAdapter.GetAddressTask();
myClass.execute();
But, if you are going to be needing this in multiple activities, then it is probably worth it to take it out of that class and put it in its own file.
If you will need to update your UI from the task, you can see this answer on using an interface
with a callback to your calling Activity
.
Upvotes: 0