我正在編碼一個Android字典應用程序。但我得到這個錯誤: 當我輸入EditText時,我會調用onTextChanged(),在這個方法中我執行一個AsyncTask線程。每次輸入字符時,應用程序都會調用onTextChange()並執行AsyncTask。例如,我輸入「da」應用程序將在數據庫中搜索「da%」這個單詞,我繼續輸入「dat」它將啓動一個新的AsyncTask線程並在數據庫中搜索「dat%」。但2線程創建並在DB中搜索,它會在返回第二個線程之前執行第一個線程(我想在執行線程2之前停止線程1)。這些問題使我的應用運行速度非常慢。如何重新啓動搜索AsyncTask線程時Edditext onTextChanged()
這是我的代碼:
的EditText上的功能:
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
keyword = txtKeyword.getText().toString().trim();
new Searching().execute("500");
}
});
的的AsyncTask類:
private class Searching extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
publishProgress("Searching...");
try {
searchlist = search(keyword);//this method will search in DB (SELECT * FFROM dictionary where word like 'da%';)
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return null;
}
@Override
protected void onPostExecute(String result) {
adapter.setListView(searchlist);
lvData.setAdapter(adapter);
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(String... text) {
txtResult.setText(text[0]);
}
}