我有一个AutoCompleteTextView,我希望通过在线API填充数据。我一直在关注这个指南
哪个工作得很好,但我现在正在尝试编辑getFilter
方法来发出HTTP请求,获取数据并对其进行处理。我已经使用Fuel https://github.com/kittinunf/Fuel了。
目前我编写的代码是:
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<Location> books = findLocation(mContext, constraint.toString());
// Assign the data to the FilterResults
filterResults.values = books;
filterResults.count = books.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultList = (List<Location>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}};
return filter;
}
/**
* Returns a search result for the given book title.
*/
private List<Location> findLocation(Context context, String bookTitle) {
List<Pair<String, String>> params = new ArrayList<>();
params.add(new Pair<>("searchterm", bookTitle));
Fuel.post("https://...search.php", params).responseString(new Handler<String>() {
@Override
public void failure(@NotNull Request request, @NotNull Response response, @NotNull FuelError error) {
}
@Override
public void success(@NotNull Request request, @NotNull Response response, String data) {
List<Location> downloaded = new ArrayList<Location>();
try {
JSONObject obj = new JSONObject(data);
if (obj.has("success")){
JSONArray success = obj.getJSONArray("success");
for(int i = 0 ; i < success.length(); i++) {
Location newlocation = new Location();
newlocation.setLocationID(success.getJSONObject(i).getString("TermID"));
newlocation.setLocationName(success.getJSONObject(i).getString("UniqueTerm"));
downloaded.add(newlocation);
}
}
} catch (Throwable t) {
}
}
});
return null;
}
当然,问题在于HTTP请求是异步完成的,因此构建的Locations数组不会被分配给AutoCompleteTextView。
一旦请求成功,我不确定修改代码以更新AutoCompleteTextView的最佳方法。