0

我正在編碼一個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]); 
    } 
} 

回答

0

您的性能問題很可能與您的LIKE查詢有關,該查詢不使用索引。如果您需要這種類型的查詢,請考慮設置結果數量的限制(如果您還沒有的話)。

也許應該考慮使用FTS,如解釋here所述。

考慮將此與異步遊標LoaderManager一起使用,它還可以處理遊標的生存期。

所有告訴如果你走這條路線,你可能會發現你不需要取消查詢一旦它在飛行中。