2013-08-16 85 views
0

Goodmorning, 我在我的android應用程序上啓動了一個按鈕,通過AsyncTask在網絡上啓動搜索(通過谷歌端點)。我的問題是,在完成AsyncTask之前,按鈕不會「解除」,這可能需要幾秒鐘的時間。當互聯網連接速度很慢時,甚至會導致應用程序崩潰,無論如何應用程序在AsyncTask完成之前完全停滯。現在使用AsyncTask的原因恰恰是爲了消除這個問題,所以我真的不知道發生了什麼!AsyncTask與OnClick速度慢

這裏是OnClickListener:

SearchListener = new OnClickListener() { 
    @Override 
    public void onClick(View v) {  
     String cname=TextCourse.getText().toString(); 
     if (!cname.isEmpty()){ 
      try { 
       CollectionResponseWine listavini= new QueryWinesTask(messageEndpoint,cname,5).execute().get(); 
      } catch (InterruptedException e) { 
       showDialog("Errore ricerca"); 
       e.printStackTrace(); 
      } catch (ExecutionException e) { 
       showDialog("Errore ricerca"); 
       e.printStackTrace(); 
      }    
     } else{ 
      showDialog("Inserisci un piatto"); 
     } 
    } 
}; 

這裏是正在調用的AsyncTask:

private class QueryWinesTask 
extends AsyncTask<Void, Void, CollectionResponseWine> { 
    Exception exceptionThrown = null; 
    MessageEndpoint messageEndpoint; 
    String cname; 
    Integer limit; 

    public QueryWinesTask(MessageEndpoint messageEndpoint, String cname, Integer limit) { 
     this.messageEndpoint = messageEndpoint; 
     this.cname=cname; 
     this.limit=limit; 
    } 

    @Override 
    protected CollectionResponseWine doInBackground(Void... params) { 
     try { 
      CollectionResponseWine wines = messageEndpoint.listwines().setCoursename(cname).setLimit(limit).execute();      
      return wines; 
     } catch (IOException e) { 
      exceptionThrown = e; 
      return null; 
      //Handle exception in PostExecute 
     }    
    } 

    protected void onPostExecute(CollectionResponseWine wines) { 
     // Check if exception was thrown 
     if (exceptionThrown != null) { 
      Log.e(RegisterActivity.class.getName(), 
        "Exception when listing Messages", exceptionThrown); 
      showDialog("Non ci sono vini associati al tuo piatto. Aggiungine uno!"); 
     } 
     else { 

      messageView.setText("Vini piu' votati per " + 
        cname + ":\n\n"); 
      for(Wine wine : wines.getItems()) { 
       messageView.append(wine.getName() + " (" + wine.getScore() + ")\n"); 
      } 
     } 
    } 
} 

回答

3

...execute().get()阻止。它使UI線程等待任務完成。

不要做get()。使用onPostExecute()獲取任務的結果(wines)並更新UI。

+0

謝謝!它現在看起來很傻,但我看不到它:) – splinter123