2013-04-16 37 views
0

我在我的适配器类AsyncTask当我第一次调用它工作正常。但是当我第二次打电话时,它不起作用。调用多次相同的AsyncTask在适配器类按钮点击方法

我知道当我们想在活动类中多次调用同一个任务时,我们必须调用new MyTask.execute()。但是这里是在非活动类(即Adapter类)中创建我的任务,因此无法实例化我的任务。我该如何解决这个问题?请提供任何解决方案。

这是我的代码:

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(); 
    } 
}; 

回答

2

但是我在这里创建了非活动类(即适配器类)的任务,以便我在这里无法实例化我的任务。

这是不正确的。你可以从你希望的任何类中启动一个AsyncTask,并保证doInBackground将在一个单独的线程中执行,而被调用线程中的其他方法(通常是UI Looper线程)将被执行。

要叫它几种类型,你应该创建一个新的类与它这样的:

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(); 
    } 
}; 

,然后从你的代码(任何地方,适配器或活动,或片段,甚至你调用一个循环)

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...); 
相关问题