aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/search/AutoCompleteAdapter.java
blob: 21cf089ff4c65ee1e6802c04d0808ee46b0a178b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package cgeo.geocaching.search;

import org.apache.commons.lang3.StringUtils;

import rx.functions.Func1;

import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;

/**
 * The standard auto completion only matches user input at word boundaries. Therefore searching "est" will not match
 * "test". This adapter matches everywhere.
 *
 */
public class AutoCompleteAdapter extends ArrayAdapter<String> {

    private final static String[] EMPTY = new String[0];
    private String[] suggestions = EMPTY;
    private final Func1<String, String[]> suggestionFunction;

    public AutoCompleteAdapter(final Context context, final int textViewResourceId, final Func1<String, String[]> suggestionFunction) {
        super(context, textViewResourceId);
        this.suggestionFunction = suggestionFunction;
    }

    @Override
    public int getCount() {
        return suggestions.length;
    }

    @Override
    public String getItem(final int index) {
        return suggestions[index];
    }

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

            @Override
            protected FilterResults performFiltering(final CharSequence constraint) {
                final FilterResults filterResults = new FilterResults();
                if (constraint == null) {
                    return filterResults;
                }
                final String trimmed = StringUtils.trim(constraint.toString());
                if (StringUtils.length(trimmed) >= 2) {
                    final String[] newResults = suggestionFunction.call(trimmed);

                    // Assign the data to the FilterResults, but do not yet store in the global member.
                    // Otherwise we might invalidate the adapter and cause an IllegalStateException.
                    filterResults.values = newResults;
                    filterResults.count = newResults.length;
                }
                return filterResults;
            }

            @Override
            protected void publishResults(final CharSequence constraint, final FilterResults filterResults) {
                if (filterResults != null && filterResults.count > 0) {
                    suggestions = (String[]) filterResults.values;
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
            }
        };
    }
}