Reusing Fragments - Filtering Favourite Coffees

As mentioned in the Lectures, a ListView supports filtering of elements via its adapter. In this step we will associate our custom filter (CoffeeFilter.java) with our CoffeeFragment so that we have the ability to filter this list whatever way we want, on any screen we want.

Our Custom Filter - CoffeeFilter.java

First of all, familarise yourself with the (already supplied) CoffeeFilter class. Pay particular attention to the two methods that had to be implemented to actually filter the data and then 'publish' the results and make sure you understand what's going on.

Next, have a look at the constructor

public CoffeeFilter(List<Coffee> originalCoffeeList, String filterText,
            CoffeeListAdapter adapter) {
        super();
        this.originalCoffeeList = originalCoffeeList;
        this.filterText = filterText;
        this.adapter = adapter;
    }

and see if you can create an instance called coffeeFilter inside our CoffeeFragment without referring to the notes.

Filtering our Favourites

Once you have the filter set up, the next step is to call it's filter method correctly to filter out just the 'Favourite' coffees and display them in our list. To achieve this you'll need to call the following code (can you work out where it should go inside our CoffeeFragment?)

if (getActivity() instanceof Favourites) {
      coffeeFilter.setFilter("favourites"); // Set the filter text field from 'all' to 'favourites'
      coffeeFilter.filter(null); // Filter the data, but don't use any prefix
      listAdapter.notifyDataSetChanged(); // Update the adapter
    }

If you run the app again, and select the Favourites Button, you should now see just the 'Favourite' coffees, like so:

Note that we didn't have to modify a single line of code in our Favourites.java Activity class.

There's still a few issues with our Favourites though, if you've done some proper testing? Can you identify the bug - and how to fix it?

Next we'll look at searching our coffees by name and/or type.

results matching ""

    No results matching ""