2014-12-26 122 views
3

我的异步任务调用我活动的onCreate()方法中Android的 - 无法执行的任务:任务已经执行

my_random_task = new MyRandomTask(); 
my_random_task.setListener(this); 

final Button post_btn = (Button) findViewById(R.id.post_btn); 
post_btn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 

     EditText post_text = (EditText) findViewById(R.id.post_text); 

     if (!post_text.isEmpty()) { 
      summoner_search_task.execute(summoner_name); 
     }else{ 
      Toast.makeText(getApplicationContext(), "Please type a post text.", Toast.LENGTH_SHORT).show(); 
      post_text.requestFocus(); 
     } 

    } 
}); 

的的AsyncTask是空的,但是当我尝试再次致电的AsyncTask按下按钮,我得到

java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)

有没有什么办法,使复位的AsyncTask并能够再次运行后,我按下按钮?

+1

你必须创建的'summoner_search_task' – TronicZomB

+0

@TronicZomB一个新的实例我如何才能做到这一点?当我单击按钮时创建一个新实例... – fxuser

+3

移动my_random_task = new MyRandomTask(); my_random_task.setListener(this);'onClick'方法内部。 – stkent

回答

0

我正在传递一个CallBackListener接口,其中包含一个回调函数,在异步任务结束时触发。

所以我做了(感谢@TronicZomB和@stkent)为:

final CallBackListener cbl = this; 

final Button post_btn = (Button) findViewById(R.id.post_btn); 
post_btn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 

     EditText post_text = (EditText) findViewById(R.id.post_text); 

     if (!post_text.isEmpty()) { 
      my_random_task = new MyRandomTask(); 
      my_random_task.setListener(cbl); 
      summoner_search_task.execute(summoner_name); 
     }else{ 
      Toast.makeText(getApplicationContext(), "Please type a post text.", Toast.LENGTH_SHORT).show(); 
      post_text.requestFocus(); 
     } 

    } 
});