/*
* Copyright 2015 Yuriy Mysochenko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class CountryAutoCompleteAdapter extends BaseAdapter implements Filterable {
private Context mContext;
private List<Country> mResult = new ArrayList<>();
public CountryAutoCompleteAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return mResult.size();
}
@Override
public Country getItem(int index) {
return mResult.get(index);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
}
((TextView) convertView.findViewById(android.R.id.text1)).setText(getItem(position).getName());
return convertView;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
return null;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// filter data in UI thread instead of background one because of Realm limitation:
// the data cannot be passed across threads
if (constraint != null) {
String query = constraint.toString().toLowerCase();
mResult = filterCountries(query);
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}};
}
@NonNull
private List<Country> filterCountries(String query) {
Realm mRealm = Realm.getDefaultInstance();
return mRealm
.where(Country.class)
.beginsWith("name", query, false)
.findAll();
}
}