gpt4 book ai didi

android - 使用 Volley 库在 android 中进行增量搜索?

转载 作者:行者123 更新时间:2023-11-30 02:09:54 24 4
gpt4 key购买 nike

我以某种方式使用 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 的新手,真的需要答案。

最佳答案

首先您需要实现一个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() 在触发请求之前等待几秒钟。

关于android - 使用 Volley 库在 android 中进行增量搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30251871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com