使用JSON响应通过Spinner过滤ListView

时间:2018-01-07 07:13:24

标签: java android json listview textview

所以除了 Android / Java 之外,我还有一个有趣的小列表适配器。它首先编写了一个由扫描仪拾取的 RFID 标签的简单列表。扫描仪附带的API使这一部分变得非常简单。它后来演变为获取与扫描程序通过需要使用标记ID本身构建的URL获取的标记关联的 JSON 对象。

快进到今天,我现在正试图找出一种方法来过滤已完成的列表项,但我需要通过标记的“状态”来完成;不是实际的10位数字符串'tagTitle'。不幸的是,我现在设置的工作微调器过滤器只是通过'tagTitle'来实现,因为我无法弄清楚如何访问其他两个TextView以将它们用作约束。但是,微调器使用的数组中填充了我们系统中的所有可能状态。很明显,我选择的任何过滤器选择,列表都是空白的。

话虽如此,任何帮助我到Point-B的帮助都将非常感激。如果有更多信息我应该包括在内,请告诉我。感谢。

public class rfid_status extends UgiUiActivity implements
        UgiInventoryDelegate,
        UgiInventoryDelegate.InventoryDidStopListener,
        UgiInventoryDelegate.InventoryTagFoundListener {

    public UgiRfidConfiguration rfidConfig;
    public EPCAdapter epcAdapter;
    public List<UgiTag> tagArray = new ArrayList<>();
    public RequestQueue rQ;
    public Spinner tagSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rfid_status);
        ListView tagListView = (ListView) findViewById(R.id.tagList);
        String[] statStrings = {
                "",
                "In",
                "Filled",
                "Out",
                "Repair",
                "Lost",
                "QC",
                "Missing",
                "Sold",
                "In Transfer"
        };
        ArrayAdapter<String> statusArray = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, statStrings);
        tagSearch = (Spinner) findViewById(R.id.tagSearch);
        tagSearch.setAdapter(statusArray);
        tagSearch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String constraint = parent.getItemAtPosition(position).toString();
                epcAdapter.getFilter().filter(constraint);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do Nothing
            }
        });

        this.setDisplayDialogIfDisconnected(true);

        UgiTitleView titleView = (UgiTitleView) findViewById(R.id.status_title);
        titleView.setTheTitle(getResources().getString(R.string.status_title));
        this.configureTitleViewNavigation(titleView);
        titleView.setBatteryStatusIndicatorDisplayVersionInfoOnTouch(true);
        titleView.setUseBackgroundBasedOnUiColor(true);
        titleView.setThemeColor(ContextCompat.getColor(this, msq_black));
        titleView.setTextColorOnThemeColor(ContextCompat.getColor(this, msq_red));
        titleView.setDisplayWaveAnimationWhileScanning(true);

        rQ = Volley.newRequestQueue(this);
        rfidConfig = UgiRfidConfiguration.INVENTORY_SHORT_RANGE;
        epcAdapter = new EPCAdapter(this);
        tagListView.setAdapter(epcAdapter);
        updateUI();
    }

public class EPCAdapter extends BaseAdapter implements Filterable {

        rfid_status rfidStatus;
        List<UgiTag> origTags;

        EPCAdapter(rfid_status rfidStatus) {
            super();
            this.rfidStatus = rfidStatus;
        }

        class TagHolder {
            TextView tagNumber, tagDetails, tagStatus;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

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

        @Override
        public Object getItem(int position) {
             return position < tagArray.size() ? tagArray.get(position) : null;
        }

        @Override
        public long getItemId(int position) {
             return position < tagArray.size() ? tagArray.get(position).getEpc().hashCode() : 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final TagHolder tagHolder;
            final UgiTag ugiTag = tagArray.get(position);
            final String tagTitle = ugiTag.toString().substring(14);

            Uri.Builder jsonBuild = new Uri.Builder();
            jsonBuild.scheme("http").authority("thirdstreamv2").appendPath("utilities").appendPath("HandheldGreenScreen").appendQueryParameter("assetid", tagTitle);
            String jsonURL = jsonBuild.build().toString();

            if (convertView == null) {
                convertView = LayoutInflater.from(rfid_status.this).inflate(R.layout.tag_row, null);
                tagHolder = new TagHolder();
                tagHolder.tagNumber = (TextView) convertView.findViewById(R.id.tagHere);
                tagHolder.tagStatus = (TextView) convertView.findViewById(R.id.statHere);
                tagHolder.tagDetails = (TextView) convertView.findViewById(R.id.descHere);
                convertView.setTag(tagHolder);
            } else {
                tagHolder = (TagHolder) convertView.getTag();
            }

            JsonObjectRequest jObj = new JsonObjectRequest(Request.Method.GET, jsonURL, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        String displayIf = response.getString("display");
                        if (!displayIf.equals("true")) {
                            tagArray.remove(ugiTag);
                            notifyDataSetChanged();
                        } else {
                             tagHolder.tagNumber.setText(tagTitle);
                             tagHolder.tagStatus.setText(response.getString("status"));
                             // I need to filter by the above somehow...
                             tagHolder.tagDetails.setText(response.getString("description"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
            rQ.add(jObj);
            return convertView;
        }

        @Override
        public Filter getFilter() {
            return new Filter() {

                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    tagArray = (List<UgiTag>) results.values;
                    notifyDataSetChanged();
                }

                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults results = new FilterResults();
                    List<UgiTag> filteredTags = new ArrayList<>();
                    constraint = constraint.toString();
                    if (origTags == null) {
                        origTags = new ArrayList<>(tagArray);
                    }
                    if (constraint.length() == 0) {
                        results.count = origTags.size();
                        results.values = origTags;
                    } else {
                        for (int position = 0; position < origTags.size(); position++) {
                            UgiTag ugiTag = origTags.get(position);
                            String tagString = ugiTag.toString().substring(14);
                            if (tagString.contains(constraint)) {
                                filteredTags.add(ugiTag);
                            }
                        }
                        results.count = filteredTags.size();
                        results.values = filteredTags;
                    }
                    return results;
                }
            };
        }
    }

1 个答案:

答案 0 :(得分:0)

没关系,自己回答。我删除了我的旧数组并使用我放在一起存储JSON响应的自定义对象创建了一个新数组,而不是仅列出RFID标签(UgiTag)。当值在对象中时,我现在可以在过滤器中访问它们并将其用作约束。

public class EPCAdapter extends BaseAdapter implements Filterable {

        rfid_status rfidStatus;
        List<TagInfo> origTags = null;

        EPCAdapter(rfid_status rfidStatus) {
            super();
            this.rfidStatus = rfidStatus;
        }

        class TagHolder {
            TextView tagNumber, tagDetails, tagStatus;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

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

        @Override
        public Object getItem(int position) {
            return position < tagList.size() ? tagList.get(position) : null;
        }

        @Override
        public long getItemId(int position) {
            return position < tagList.size() ? tagList.get(position).hashCode() : 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final TagInfo tagItem = tagList.get(position);
            final String tagTitle = tagItem.getUgiTag().toString().substring(14);
            final TagHolder tagHolder;

            Uri.Builder jsonBuild = new Uri.Builder();
            jsonBuild.scheme("http").authority("thirdstreamv2").appendPath("utilities").appendPath("HandheldGreenScreen").appendQueryParameter("assetid", tagTitle);
            String jsonURL = jsonBuild.build().toString();

            if (convertView == null) {
                convertView = LayoutInflater.from(rfid_status.this).inflate(R.layout.tag_row, null);
                tagHolder = new TagHolder();
                tagHolder.tagNumber = (TextView) convertView.findViewById(R.id.tagHere);
                tagHolder.tagStatus = (TextView) convertView.findViewById(R.id.statHere);
                tagHolder.tagDetails = (TextView) convertView.findViewById(R.id.descHere);
                convertView.setTag(tagHolder);
            } else {
                tagHolder = (TagHolder) convertView.getTag();
            }

            JsonObjectRequest jObj = new JsonObjectRequest(Request.Method.GET, jsonURL, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        tagItem.setTagStatus(response.getString("status"));
                        tagItem.setTagDescription(response.getString("description"));
                        tagItem.setTagDisplay(response.getString("display"));

                        tagHolder.tagNumber.setText(tagTitle);
                        tagHolder.tagStatus.setText(tagItem.getTagStatus());
                        tagHolder.tagDetails.setText(tagItem.getTagDescription());

                        if (!tagItem.getTagDisplay().equals("true")) {
                            tagList.remove(tagItem);
                            notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
            rQ.add(jObj);
            return convertView;
        }

        @Override
        public Filter getFilter() {
            return new Filter() {

                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults results = new FilterResults();
                    List<TagInfo> filteredTags = new ArrayList<>();
                    constraint = constraint.toString();
                    if (origTags == null) {
                        origTags = new ArrayList<>(tagList);
                    }
                    if (constraint.length() == 0) {
                        results.count = origTags.size();
                        results.values = origTags;
                    } else {
                        for (int position = 0; position < origTags.size(); position++) {
                            TagInfo origPos = origTags.get(position);
                            String tagString = origPos.getTagStatus();
                            if (tagString.contains(constraint)) {
                                filteredTags.add(origPos);
                            }
                        }
                        results.count = filteredTags.size();
                        results.values = filteredTags;
                    }
                    return results;
                }

                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    tagList = (List<TagInfo>) results.values;
                    notifyDataSetChanged();
                }
            };
        }
    }