2012-07-31 131 views
0

我有一個應用程序,其中有一個AutoCompleteTextView。在每個文本更改事件中,應用程序都會轉到Web以從Internet上檢索一些內容並填充TextView的下拉列表。我使用AsyncTask來完成網頁內容的讀取。但是,如果在接收和填充內容之前鍵入新文本,應用程序將掛起直到獲取舊內容。有沒有辦法解決這個問題?Android:AsyncTask不按預期方式工作

我的AsyncTask是如下,

private class GetSuggestions extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     System.out.println("Suggestions Called()"); 
     doSearch(params[0]); // reads the web and populates the suggestions ArrayList 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     System.out.println("Adapter Called() " + suggestions.size()); 
     suggestionAdapter = new ArrayAdapter<String>(
       getApplicationContext(), R.layout.list, suggestions); 
     searchText.setAdapter(suggestionAdapter); 
    } 
} 

THX! 拉胡爾。

+0

在你的情況下,這取決於你想要完成什麼。我會說,如果下拉列表中的任何內容都與'TextView'是直接相關的,並且它始終是一個'TextView',那麼停止該進程並使用新文件重新啓動它。如果沒有,那麼你總是可以做一個等待列表並讓'onPostExecute'檢查這個列表來查看是否有下一個。 – Andy 2012-07-31 05:30:10

回答

0

您可以檢查AsyncTask是否正在運行。

public boolean isRunning() 
{ 
    if (_querymysqltask == null) return false; 
    if (_querymysqltask.getStatus() == AsyncTask.Status.FINISHED) return false; 
    else return true; 
} 

您可以取消任務以重新啓動它,或者等待它結束。

0
if(task == null) 
{ 
    task = new GetSuggestions(); 
    task.execute(new String[] {word}); 
} 
else 
{ 
    task.cancel(true); 
    task = new GetSuggestions(); 
    task.execute(new String[] {word}); 
} 

您可以使用新輸入的文本取消該任務並開始一個新任務。代碼將如上所示。

0

您可以顯示progressDialog,直到從網頁獲取數據。

private ProgressDialog dialog = new ProgressDialog(HomeActivity.this); 

    /** progress dialog to show user that the backup is processing. */ 
    /** application context. */ 

    protected void onPreExecute() { 
     this.dialog.setMessage("Please wait"); 
     this.dialog.show(); 
    } 


    @Override 
    protected void onPostExecute(final Boolean success) { 

     if (dialog.isShowing()) { 
      dialog.dismiss(); 
     } 
    } 
0

好像問題出在

doSearch(params[0]); // reads the web and populates the suggestions ArrayList 

doSearch()從doInBackground()被調用,所以它不應該elemnets.only觸摸UI,執行「讀網'部分從doInBackground()並從onPostExecute()填充ArrayList。