Reputation: 121
I had AsyncTask
in my adapter class when i calling first time it's working fine. But when i call second time it doesn't work.
I know when we want to call same task multiple times in activity class we have to call new MyTask.execute()
.But here am created my task in non activity class (i.e Adapter class) so here am unable to instantiate my task. How can i resolve this problem? Please provide any solution.
This is my code:
public AsyncTask<String,Void,Void> mytaskfavorite = new AsyncTask<String,Void,Void>() {
protected void onPreExecute() {
pd = new ProgressDialog(mContext);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//proDialog.setIcon(R.drawable.)
pd.setCancelable(false);
pd.show();
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
}
@Override
protected Void doInBackground(String...code) {
String buscode = code[0];
// TODO Auto-generated method stub
addFavoriteBusinessSelection.addFavoriteBusinessBusinessSelection(buscode);
System.out.println("##################################" + buscode);
return null;
}
@Override
protected void onPostExecute(Void res) {
pd.dismiss();
}
};
Upvotes: 0
Views: 1016
Reputation: 39846
But here am created my task in non activity class (i.e Adapter class) so here am unable to instantiate my task.
That is not true. The you can initiate an AsyncTask from any class you wish with the guaranteed that doInBackground will be executed in a separate thread and the other methods in the called thread (usually the UI Looper thread).
To call it several types you should create a new class with it like that:
public Class TaskFavorite extends new AsyncTask<String,Void,Void>() {
// You can optionally create a constructor to receiver parameters such as context
// for example:
private Context mContext
public TaskFavorite(Context c){
mContext = c;
}
protected void onPreExecute() {
pd = new ProgressDialog(mContext);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//proDialog.setIcon(R.drawable.)
pd.setCancelable(false);
pd.show();
// Don't use println in Android, Log. gives you a much better granular control of your logs
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
}
@Override
protected Void doInBackground(String...code) {
String buscode = code[0];
// TODO Auto-generated method stub
addFavoriteBusinessSelection.addFavoriteBusinessBusinessSelection(buscode);
System.out.println("##################################" + buscode);
return null;
}
@Override
protected void onPostExecute(Void res) {
pd.dismiss();
}
};
and then from your code (anywhere, adapter or activity, or fragment or even a loop you call)
TaskFavorite task = new TaskFavorite(getContext()); // how you get the context to pass to the constructor may vary from where you're calling it, but most adapters to have one
task.execute(... parameters...);
Upvotes: 2