multithreadingsearchview

SearchView onQueryTextSubmit runs twice while I pressed once


I am writing a search function to access a library website.And when the query string is submitted,program launches a new thread to parse infos on the web. it runs normally on AVD but my HTC DesireHD displayed the search results repeatedly,(if the real results are 1. 2. 3. it would appears to be 1. 2. 3. 1. 2. 3.). I set breakpoints at the onQueryTextSubmit method ,found that codes in method onQueryTextSubmit() were executed twice. and here is my code:

sv.setOnQueryTextListener(new OnQueryTextListener(){

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            list.clear();
            String str = null;
            try {//encoding Chinese character
                str = new String(query
                        .trim().getBytes(), "ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            SearchPost sp = new SearchPost(SEARCH_URL + str);
            new Thread(sp).start(); 
            return false;
        }
    });

protected class SearchPost implements Runnable{
    public String url = "";
    SearchPost(String urls){
        url = urls;
    }
    public SearchPost() {
    }
    @Override
    public void run() {
        Message message = handler.obtainMessage();
        message.what = DOWNLOAD_COMPLETE;
        try{
            doc = Jsoup.connect(url).get();
                handler.sendMessage(message);
        }catch(IOException e){
            e.printStackTrace();
            message.what = DOWNLOAD_FAIL;
            handler.sendMessage(message);
        }
    }
}

Solution

  • Finding out why clicking the button once causes onQueryTextSubmit to fire twice is an issue on its own that you might not be able to solve as it is controlled by the OS that might be buggy. The real question is about properly handling the case where the button is clicked twice or more in quick succession which would probably have the same effect. I suggest to have the list.clear() moved in the same place where you populate the list.