我有一个自动文本视图,可以从Web服务获取数据。我已经实现了TextChangedListener。从互联网上获取数据。每次在Textchanged上新的字符都是get和on afterTextChanged AsyncTask被调用。我想让它快速,因为如果用户手动输入文本...需要很长时间才能获取一些新数据。
textView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
seq = cs;
}
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3)
{
}
@Override
public void afterTextChanged(Editable arg0)
{
new SearchTask().execute(seq.toString().trim());
}
});
AsyncTask是..
private class SearchTask extends AsyncTask<CharSequence, Void, String>
{
ArrayAdapter<String> adapter;
String[] array;
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(CharSequence... params)
{
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(pak_url + params[0]);
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
String response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
if (response != null) {
String substr = response.split("\\(")[2].split("\\)")[0];
array = substr.split(",");
for (int i = 0; i < array.length; i++) {
array[i] = array[i].replace("'", "");
}
}
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (array != null) {
adapter = new ArrayAdapter<String>(PlayListActivity.this,
android.R.layout.simple_list_item_1, array);
textView.setAdapter(adapter);
adapter.getFilter().filter(seq);
}
/*else {
Toast.makeText(PlayListActivity.this,
"Could not connect to server try again later...",
Toast.LENGTH_LONG).show();
}*/
}
}
答案 0 :(得分:0)
您可以通过以下解决方案停止多个请求:
private SearchTask mAsync;
@Override
public void afterTextChanged(Editable arg0)
{
if(mAsync!=null) {
mAsync.cancel(true);
}
mAsync = new SearchTask().execute(seq.toString().trim());
}
现在你没有多次请求弄乱你的应用程序。
同时检查cancel()
的{{3}}。摘录内容如下:
调用此方法将导致在
onCancelled(Object)
返回后在UI线程上调用doInBackground(Object[])
。调用此方法可确保永远不会调用onPostExecute(Object)
。调用此方法后,您应该定期检查isCancelled()
从doInBackground(Object[])
返回的值,以尽早完成任务。