Bugs When Searching Through ArrayList

38 views Asked by At

I have an ArrayList of objects. I use this method whenever the user types in a searchView, that's what filterBy is. The variable byName is a boolean to determine whether we're searching by name or code. My errors are:

  1. I'm testing it using the keyword "alfalfa", but it returns extra items each time I enter a letter (I'm checking by doing the same thing on the database itself).
  2. If I click the switch (changes the byName boolean) while there is text in the searchView, it will continue removing items until there is nothing left.
  3. Deleting text in the searchView will continue to remove text as well (this one baffles me, as the list it's removing items from will only be set in this method).

Any thoughts on what's causing this?

private void displayProducts() {
    final Querier querier = new Querier(this);
    ProductListAdapter productListAdapter;

    if (filterBy.equals("")) {
        products = querier.getProductsListing();

        productListAdapter = new ProductListAdapter(this, products.getProductsList(), byName);
    } else {
        Products ps = products;

        for (int i = 0; i < products.getProductsList().size(); i++) {
            final Product prod = ps.getProductsList().get(i);

            if (byName) {
                if (!prod.getProductName().toLowerCase().contains(filterBy))
                    ps.getProductsList().remove(prod);

            } else if (!prod.getOrderCode().toLowerCase().contains(filterBy))
                ps.getProductsList().remove(prod);
        }

        Log.v("removed some junk, now there are", String.valueOf(ps.getProductsList().size()));

        productListAdapter = new ProductListAdapter(this, ps.getProductsList(), byName);
    }

    productsLinearLayout.setAdapter(productListAdapter);
}
1

There are 1 answers

0
Cody Harness On BEST ANSWER

In the event that this is helpful to someone else down the line, here's how I fixed it.

private void displayProducts() {
    final Querier querier = new Querier(this);
    ProductListAdapter productListAdapter;
    products = querier.getProductsListing();

    if (filterBy.equals(""))
        productListAdapter = new ProductListAdapter(this, products.getProductsList(), byName);
    else {
        ArrayList<Product> ps = new ArrayList<>(products.getProductsList());

        for (Product p : products.getProductsList()) {
            if (byName) {
                if (!p.getProductName().toLowerCase().contains(filterBy))
                    ps.remove(p);

            } else {
                if (!p.getOrderCode().toLowerCase().contains(filterBy))
                    ps.remove(p);
            }
        }

        Log.v("removed some junk, now there are", String.valueOf(ps.size()));

        productListAdapter = new ProductListAdapter(this, ps, byName);
    }

    productsLinearLayout.setAdapter(productListAdapter);
}