从服务器搜索json数组的搜索栏

时间:2015-01-31 18:43:30

标签: java android arrays json android-studio

我正在尝试创建搜索栏,搜索服务器中的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对象。

1 个答案:

答案 0 :(得分:1)

解析JSON并将结果放入ArrayList。 您需要ArrayAdapter来实现Filterable界面,并将其设置为ListView

您的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.的代码