【问题标题】:Incremental search in android using Volley library?使用 Volley 库在 android 中进行增量搜索?
【发布时间】:2015-05-15 05:07:12
【问题描述】:

我以某种方式使用 AsyncTask 在 android 中实现了增量搜索。在增量搜索中,为编辑文本中输入的每个字符调用 API 以从服务器获取建议。例如,

User types a -> API is called.
User types ab -> API is called.
User types abc -> API is called. 

这会分别对 a、ab 和 abc 进行三个 API 调用。如果用户仍在键入,则所有先前的请求(例如 a 和 ab 的请求)将被取消,并且将仅处理最后一个请求 (abc) 以避免延迟。

现在我想使用 Volley 库来实现它以获得更好的性能。任何人都可以帮助我如何使用 volley 来实现此功能,特别是取消所有先前请求并仅提供最后一个请求以从服务器获取建议的机制。

注意:我找不到这方面的信息,因此将其发布在此处。请指导我,因为我是 android 新手,真的需要回答。

【问题讨论】:

    标签: android android-asynctask android-volley incremental-search


    【解决方案1】:

    首先你需要实现一个TextWatcher 来监听编辑文本的变化。 根据更改文本的要求,您取消并将请求添加到队列。

    private RequestQueue queue = VolleyUtils.getRequestQueue();
    
    
    private static final String VOLLEY_TAG = "VT";
    private EditText editText;
    ...
    
     TextWatcher textChangedListener = new TextWatcher() {
    
              @Override
              public void afterTextChanged(Editable s) {}
    
              @Override
              public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
              @Override
              public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                if (s.length() != 0) {
                    // first cancel the current request with that tag
                    queue.cancelAll(VOLLEY_TAG);
                    // and then add a new one to queue
                    StringRequest stringRequest = 
                         new StringRequest("http://blabla/servlet?param=" + s, 
                         new Listener<String>() {
                           // request callbacks
                         };
                    stringRequest.setTag(VOLLEY_TAG);
                    queue.add(stringRequest);
                } 
            }
      };
    
    editText.addTextChangedListener(textChangedListener);
    

    请记住,这种设计会占用带宽。更好的方法是使用Handler.post() 在触发请求之前等待几秒钟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 2015-07-16
      • 2019-01-11
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 2011-11-06
      相关资源
      最近更新 更多