Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid: restart search thread
    primarykey
    data
    text
    <p>I have a simple <code>EditText</code> with a <code>TextChangedListener</code> and a <code>ListView</code>.</p> <p>The <code>onTextChanged</code> method will call the following <code>restartSearch</code> method, so the current search thread should be restarted while typing into the <code>EditText</code>.</p> <p>The <code>search</code> method just adds matching items to the <code>ListView</code>.</p> <p>When the <code>searchThread</code> is still alive, I want to cancel and restart the search so the UI doesn't freeze while typing and it doesn't take so long.</p> <pre><code>Thread searchThread; private void restartSearch(CharSequence cs){ query = cs; if(searchThread != null &amp;&amp; searchThread.isAlive()){ searchThread.interrupt(); } searchThread = new Thread(new Runnable() { public void run() { if(!lastSearch.equals(query)) search(query); } }); searchThread.start(); } </code></pre> <p>The method from where I call it:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText etSearch = ((EditText) findViewById(R.id.etSearch)); //... etSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub restartSearch(s); } //... }); } </code></pre> <p>and another (from where I also update the UI):</p> <pre><code>final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==1){ //... adapter.notifyDataSetChanged(); restartSearch(lastSearch); } else if(msg.what==2) adapter.notifyDataSetChanged(); super.handleMessage(msg); } }; </code></pre> <p>the message <code>msg</code> is sent from the <code>search</code> method to update the UI:</p> <pre><code>private void search(CharSequence s){ searchResults.clear(); if(!s.toString().equals("")){ for(int i=0; i&lt;vocsCount; i++){ try{ getResult(i, 0, 2,s); getResult(i, 1, 1,s); }catch(Exception ex){} } Collections.sort(searchResults); } Message msg = handler.obtainMessage(); msg.what = 2; handler.sendMessage(msg); lastSearch = s; } </code></pre> <p>So as it creates a new <code>Runnable</code> every time, it seems as if they all run parallel, because all search-items are added multiple times to the ListView.</p> <p>How can I avoid this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload