【问题标题】:Searchbar that searches through a json array from the server从服务器搜索 json 数组的搜索栏
【发布时间】:2015-03-31 01:37:11
【问题描述】:

我正在尝试创建搜索栏,用于搜索来自服务器的 json 数据并将结果显示在 ListView 中。数据是数组的形式。例如

ProductList: [

{ ProductCode: "10012010",
  ProductName: "Kell", 
  ProductGrammage: "120 gm", 
  ProductBarcode: "890123456789", 
  ProductCatCode: "40", 
  ProductCatName: "Packed Food and Condiments",
  ProductSubCode: "4001", 
  ProductSubCodeName: "Breakfast & Cereals",
  ProductMRP: "120", 
  ProductBBPrice: "115" },

ect...

]

假设我在搜索栏中输入 Kell。我希望这个 Kell 对象在我的列表视图中弹出。

【问题讨论】:

标签: java android arrays json android-studio


【解决方案1】:

解析 JSON 并将结果放入 ArrayList。 您需要一个实现Filterable 接口并将其设置为ListViewArrayAdapter

您的ArrayAdapter 应类似于:

private class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
    private ArrayList<String> resultList;

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
            }};
        return filter;
    }
}

来自here.的代码

【讨论】:

  • 谢谢!我应该如何使用从我的 JSON 数据中获得的数组创建一个 ArrayList?
猜你喜欢
  • 1970-01-01
  • 2019-05-27
  • 2018-12-14
  • 2021-12-23
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
相关资源
最近更新 更多