2012-07-31 159 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。