on JDK 1.8
tried casting many ways but none working for me.
public class CountryAdapter extends ArrayAdapter<CountryModel> {
private Context context;
private List<CountryModel> countryModelList;
private List<CountryModel> countryModelListFiltered;
public CountryAdapter(Context context, List<CountryModel> countryModelList) {
super(context, R.layout.custom_list_item, countryModelList);
this.context = context;
this.countryModelList = countryModelList;
this.countryModelListFiltered = countryModelList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//Instantiates a layout XML file into its corresponding View objects.
#SuppressLint("ViewHolder")
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_list_item, null, true);
TextView tvCountryName = view.findViewById(R.id.tvCountryName);
ImageView countryFlag = view.findViewById(R.id.imageFlag);
tvCountryName.setText(countryModelListFiltered.get(position).getCountry());
//using glide library to set image to image View.
Glide.with(context).load(countryModelListFiltered.get(position).getFlag()).into(countryFlag);
return view;
}
#Override
public int getCount() {
return countryModelListFiltered.size();
}
#Nullable
#Override
public CountryModel getItem(int position) {
return countryModelListFiltered.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
//Filter Logic
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint == null || constraint.length() == 0) {
filterResults.count = countryModelList.size();
filterResults.values = countryModelList;
} else {
List<CountryModel> resultModel = new ArrayList<>();
String searchString = constraint.toString().toLowerCase();
for (CountryModel itemModel:countryModelList) {
if (itemModel.getCountry().toLowerCase().contains(searchString)) {
resultModel.add(itemModel);
}
filterResults.count = resultModel.size();
filterResults.values = itemModel;
}
}
return filterResults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
Log.d("Cast:", "publishResults: " + results.values.toString());
countryModelListFiltered = ((List<CountryModel>) results.values);
AffectedCountries.countryModelList = (List<CountryModel>) results.values;
notifyDataSetChanged();
}
};
return filter;
}
}
I have checked you code .. problem is you are assigning wrong value to filterResults also at wrong place (inside loop). Your code should look like below .
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint == null || constraint.length() == 0) {
filterResults.count = countryModelList.size();
filterResults.values = countryModelList;
} else {
List<CountryModel> resultModel = new ArrayList<>();
String searchString = constraint.toString().toLowerCase();
for (CountryModel itemModel:countryModelList) {
if (itemModel.getCountry().toLowerCase().contains(searchString)) {
resultModel.add(itemModel);
}
}
filterResults.count = resultModel.size();
filterResults.values = resultModel;
}
return filterResults;
}
Related
I want to filter some ArrayList of datas with search,
In my Activity's onCreate:
arrayList = getListItemData();
filteredArrayList = new ArrayList<>();
filteredArrayList.addAll(arrayList);
adapter = new NameAdapter(filteredArrayList);
itemList.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
my adapter with filterable:
public class NameAdapter extends RecyclerView.Adapter<NameAdapter.ViewHolder> implements Filterable {
private ArrayList<Name> arrayList;
private CustomFilter filter;
public NameAdapter(ArrayList<Branch> items) {
arrayList = items;
filter = new CustomFilter(NameAdapter.this);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_name, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.data = arrayList.get(position);
}
#Override
public int getItemCount() {
return branchArrayList.size();
}
#Override
public Filter getFilter() {
return filter;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View view;
public final TextView branch;
public Name data;
public ViewHolder(View view) {
super(view);
this.view = view;
branch = view.findViewById(R.id.textView_name);
}
}
public class CustomFilter extends Filter {
private NameAdapter adapter;
private CustomFilter(NameAdapter adapter) {
super();
this.adapter = adapter;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredArrayList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredArrayList.addAll(arrayList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final Name name : arrayList) {
if (name.getName().toLowerCase().startsWith(filterPattern)) {
filteredBranchArrayList.add(name);
}
}
}
results.values = filteredArrayList;
results.count = filteredArrayList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
this.adapter.notifyDataSetChanged();
}
}
}
filter doesn't work for some reason it clears the recyclerview when I type something
1st make a copy of the branchArrayList in the constructor.like this :-
private ArrayList<Branch> branchCopy = new ArrayList<>;
public BranchAdapter(ArrayList<Branch> items) {
branchArrayList = items;
branchCopy.addAll(items);
filter = new CustomFilter(BranchAdapter.this);
}
your performingFilter
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Branch> branchFilter = new ArrayList<>;
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
branchFilter.addAll(branchArrayList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final Branch branch : branchCopy) {
if (branch.getBranchName().toLowerCase().startsWith(filterPattern)) {
branchFilter.add(branch);
}
}
}
results.values = branchFilter ;
results.count = branchFilter.size();
return results;
}
Your publishResults
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
branchArrayList = (ArrayList<Branch>) results.values; // you have done nothing with the filter results
notifyDataSetChanged();
}
Before notifying change the mainList !!
branchArrayList = (ArrayList<Branch>) results.values;
add this line to publishResults
You have done NOTHING with the filter results
Try to change your Adapter as
public class BranchAdapter extends RecyclerView.Adapter<BranchAdapter.ViewHolder> implements Filterable {
private ArrayList<Branch> mArrayList;
private ArrayList<Branch> mFilteredList;
private CustomFilter filter;
public BranchAdapter(ArrayList<Branch> items) {
mArrayList = items;
mFilteredList = items;
filter = new CustomFilter(BranchAdapter.this);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_branch, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.data = branchArrayList.get(position);
holder.branch.setText(String.valueOf(mArrayList.get(position).getBranchCode() + " / " + mArrayList.get(position).getBranchName()));
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public Filter getFilter() {
return filter;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View view;
public final TextView branch;
public Branch data;
public ViewHolder(View view) {
super(view);
this.view = view;
branch = view.findViewById(R.id.textView_branch);
}
}
public class CustomFilter extends Filter {
private BranchAdapter adapter;
private CustomFilter(BranchAdapter adapter) {
super();
this.adapter = adapter;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = mArrayList;
} else {
ArrayList<Branch> filteredList = new ArrayList<>();
for (Branch branch : mArrayList) {
if (branch.getBranchName().toLowerCase().contains(charString)) {
filteredList.add(branch);
}
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilteredList = (ArrayList<Branch>) filterResults.values;
notifyDataSetChanged();
// this.adapter.notifyDataSetChanged();
}
}
}
update your branchArrayList in the publishResults method before doing notifyDataSetChanged
update your PublishResults() with below code
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredBranchArrayList = (ArrayList<Branch>) filterResults.values;
notifyDataSetChanged();
}
I am implementing autosearchTextView and I am getting data from web service.The API get hit when char value is 3. I refer this link https://github.com/kyasar/markod/blob/master/app/src/main/java/com/dopamin/markod/adapter/ProductSearchAdapter.java. and this is also
http://makovkastar.github.io/blog/2014/04/12/android-autocompletetextview-with-suggestions-from-a-web-service/
When I enter 3 char the publishResults() method trigger and so getting no drop down. I debugged and I found web service get called and but before it This publishResults() method triggered. I have to spend a lot of time to do in R&D. Please Help me out.
mMutualFundAdapter = new PrimaryContractAdapter(CreateNoteActivityNew.this); primary_atv.setThreshold(3);//will start working from 3 character
//setting the adapter data into the AutoCompleteTextView
primary_atv.setAdapter(mMutualFundAdapter);
primary_atv.setLoadingIndicator(
(android.widget.ProgressBar) findViewById(R.id.pb_loading_indicator));
primary_atv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
PrimaryContract primaryContract = (PrimaryContract) adapterView.getItemAtPosition(position);
primary_atv.setText(primaryContract.getContract());
}
});
Adapter -
public PrimarySearchAdapter(Context context, ArrayList<PrimaryContract> resultList) {
mContext = context;
this.resultList = resultList;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public PrimaryContract getItem(int index) {
return resultList.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(R.layout.drop_down_layout, parent, false);
}
((TextView) convertView.findViewById(R.id.heading)).setText(getItem(position).getText());
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
findData(mContext, constraint.toString());
if (contractArrayList != null && contractArrayList.size()>0) {
// Assign the data to the FilterResults
filterResults.values = contractArrayList;
filterResults.count = contractArrayList.size();
}
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultList = ( ArrayList<PrimaryContract>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}};
return filter;
}
private void findData(Context context, String bookTitle) {
// this finddata() for getting response from REST API using retrofit
contractArrayList = new ArrayList<>();
String url = "http://se.com/publisher_api/primaryContracts?keyword=";
url = url + bookTitle;
ApiRequestResponse apiRequestResponse = new ApiRequestResponse();
final OnResponseReceiveEvent onResponseReceiveEvent = new OnResponseReceiveEvent() {
#Override
public void getSuccess(Object obj) {
if (obj != null) {
createNoteModel = (CreateNoteModel) obj;
if (createNoteModel.getPrimaryContracts() != null && createNoteModel.getPrimaryContracts().size()>0){
if (contractArrayList != null) {
contractArrayList.clear();
contractArrayList = createNoteModel.getPrimaryContracts();
}
}
}
notifyDataSetChanged();
}
// I have followed as I given two links
#Override
public Object getFailure() {
return null;
}
};
apiRequestResponse.getDropDownData(onResponseReceiveEvent, url);
}
}
I have a list of merchants, I am applying filter to it to search by address or a name, filter works fine. it gives proper list of filtered results. But if I again empty the edit text I should see the original list, but I see different count than the original.
Example, in list I have 7 merchants, I do filter it and it shows two filtered merchants in the list, and now if I empty the edit text I see only 5 merchants , unable to see the original list of 7 merchants.
Adapter:
public class SearchedMerchantsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
static final int LOAD_MERCHANTS = 0;
private Context context;
public ArrayList<Merchants> list;
public ArrayList<Merchants> baselist = new ArrayList<>();
public SearchedMerchantsAdapter(Context context, ArrayList<Merchants> list) {
this.context = context;
this.list = list;
this.baselist = list;
}
#Override
public int getItemViewType(int position) {
Object obj = list.get(position);
if (obj instanceof Merchants) return LOAD_MERCHANTS;
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = holder.getItemViewType();
switch (viewType) {
case LOAD_MERCHANTS:
LoadSearchedMerchants loadSearchedMerchants = (LoadSearchedMerchants) holder;
retriveAllMerchants(loadSearchedMerchants, position);
break;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (viewType) {
case LOAD_MERCHANTS:
View v_image_msg = inflater.inflate(R.layout.search_merchant_layout, parent, false);
viewHolder = new LoadSearchedMerchants(v_image_msg);
break;
}
return viewHolder;
}
#Override
public int getItemCount() {
return list.size();
}
public void retriveAllMerchants(final LoadSearchedMerchants holder, int position) {
final Merchants data = (Merchants) list.get(position);
holder.tv_kiarana_name.setText(data.getKirana_name());
holder.tv_address.setText(data.getMerchant_address());
holder.lay_row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, MerchantProfileActivity.class);
i.putExtra("cont_name",data.getMerchant_name());
i.putExtra("kirana_name",data.getKirana_name());
i.putExtra("email_id",data.getEmail_id());
i.putExtra("phone_no",data.getPhone());
i.putExtra("address",data.getMerchant_address());
context.startActivity(i);
}
});
holder.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final SessionData sessionData;
final String sessionUserId,access_token;
sessionData=new SessionData(context);
sessionUserId = sessionData.getString("user_id","-1");
access_token = sessionData.getString("api_key", "-1");
new SendRequestAsyncTask(context).execute(sessionUserId,access_token,data.getMerchant_id().toString());
}
});
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Merchants> results = new ArrayList<>();
if (constraint != null) {
if (baselist != null && baselist.size() > 0) {
for (final Merchants g : baselist) {
if (g.getKirana_name()
.contains(constraint.toString()) || g.getMerchant_address().contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<Merchants>) results.values;
notifyDataSetChanged();
}
};
}
}
What can be the reason for this? Thank you..
Create this method in adapter:
public Item getItemAtPosition(int position)
{
return list.get(position);
}
Now, when click action occurs just call this method:
adapter.getItemAtPosition(position).getMerchant_name()
Can you try this ?
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Merchants> results = new ArrayList<>();
if (charSequence != null && charSequence.length() > 0) {
if (baselist != null && baselist.size() > 0) {
for (final Merchants g : baselist) {
if (g.getKirana_name()
.contains(constraint.toString()) || g.getMerchant_address().contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
oReturn.count = results.size();
}
else
{
oReturn.values = baselist;
oReturn.count = baselist.size();
}
return oReturn;
}
Update
Create one Method in Adapter.. Comment out getFilter() and interface Filterable
public void filterData(String compareString)
{
list.clear();
if (baselist != null && baselist.size() > 0) {
for (final Merchants g : baselist) {
if (g.getKirana_name()
.contains(compareString) || g.getMerchant_address().contains(compareString))
list.add(g);
}
}
notifyDataSetChanged();
}
And Last call this Method From your edittext change listener
like adapter.filterData("StringwhichisChangedFromEdittext")
Hope this help.
Return the entire list if user enters nothing
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Merchants> results = new ArrayList<>();
if(TextUtils.isEmpty(constraint)){
oReturn.values = baselist==null?new ArrayList() : baselist ;
return oReturn.values ;
}
if (constraint != null) {
if (baselist != null && baselist.size() > 0) {
for (final Merchants g : baselist) {
if (g.getKirana_name()
.contains(constraint.toString()) || g.getMerchant_address().contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<Merchants>) results.values;
notifyDataSetChanged();
}
};
}
I am implementing a filter to my custom object list. Filter is working, but if I filter the list I get the filtered result list and again if I try to filter with different word the list seems empty.
Original list is not seen when filtered.
Adapter :
public class ItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable{
static final int LOAD_ORDERITEMS = 0;
private Context context;
private List<OrderItem> list;
private AddOrderFragment addOrderFragment;
public ItemsAdapter(Context context, List<OrderItem> list) {
this.context = context;
this.list = list;
this.addOrderFragment = addOrderFragment;
}
#Override
public int getItemViewType(int position) {
Object obj = list.get(position);
if (obj instanceof OrderItem) return LOAD_ORDERITEMS;
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = holder.getItemViewType();
switch (viewType) {
case LOAD_ORDERITEMS:
LoadOrderItemsHolder loadOrderItemsHolder = (LoadOrderItemsHolder) holder;
retrieveAllOrderItem(loadOrderItemsHolder,position);
break;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (viewType) {
case LOAD_ORDERITEMS:
View v_image_msg = inflater.inflate(R.layout.item_layout, parent, false);
viewHolder = new LoadOrderItemsHolder(v_image_msg);
break;
}
return viewHolder;
}
#Override
public int getItemCount() {
return list.size();
}
public void retrieveAllOrderItem(final LoadOrderItemsHolder holder, int position) {
final OrderItem data = (OrderItem) list.get(position);
holder.txtItemName.setText(data.getItemName());
String unit = data.getQuantity() + " " + data.getUnit();
holder.txtItemQty.setText(unit);
holder.relativeRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((SearchActivity)context).linearLayoutRecycleView.setVisibility(View.GONE);
((SearchActivity)context).textInput_Item_Unit.setVisibility(View.VISIBLE);
((SearchActivity)context).textInput_Item_quantity.setVisibility(View.VISIBLE);
((SearchActivity)context).textInput_Item_name.setBackgroundResource(0);
((SearchActivity)context).edt_Item_Name.setText(data.getItemName());
((SearchActivity)context).edt_Item_quantity.setText(data.getQuantity());
((SearchActivity)context).edt_Item_Unit.setText(data.getUnit());
}
});
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<OrderItem> results = new ArrayList<OrderItem>();
if (constraint != null) {
if (list != null && list.size() > 0) {
for (final OrderItem g : list) {
if (g.getItemName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<OrderItem>) results.values;
notifyDataSetChanged();
}
};
}
}
Please help.. Thank you..
Use this code
static final int LOAD_ORDERITEMS = 0;
private Context context;
private List<OrderItem> list;
private List<OrderItem> baselist = new ArrayList<>();
private AddOrderFragment addOrderFragment;
public ItemsAdapter(Context context, List<OrderItem> list) {
this.context = context;
this.list = list;
this.baselist = list;
this.addOrderFragment = addOrderFragment;
}
And in Filter
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<OrderItem> results = new ArrayList<OrderItem>();
if (constraint != null) {
if (baselist != null && baselist.size() > 0) {
for (final OrderItem g : baselist ) {
if (g.getItemName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<OrderItem>) results.values;
notifyDataSetChanged();
}
};
}
As We need to store original list in separate array list, we need to get filter data from that.
I created custom adapter by extending BaseAdapter and implementing Filterable interface. This adapter is used for suggest phone number to user when they type a contact number or contact person name.ArrayList<String> data contain those data with the pattern of "person name:number" which are extracted from phone.
It's working find except for one issue. If I search for contacts start with letter "A" it's show the data correctly. If I delete that and type "B" again it shows both contacts start with "A" and "B". I know that I have to clear ArrayList<String> matchedResults(Check the code) in some method before add new data but when I did that It gave me an empty ArrayList. In which method at which point I should do that or is there a different solution for this ?
here's the code
public class AutoCompleteAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<String> data;
private ArrayList<String> matchedResults = new ArrayList<String>();
public AutoCompleteAdapter(Context context, ArrayList<String> namesAndNumbers) {
this.context = context;
this.data = namesAndNumbers;
}
#Override
public int getCount() {
return matchedResults.size();
}
#Override
public String getItem(int position) {
return matchedResults.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_layout, parent, false);
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView numberTextView = (TextView) view.findViewById(R.id.number);
String[] split = matchedResults.get(position).split(":");
nameTextView.setText(split[0]);
numberTextView.setText(split[1]);
return view;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null || constraint.length() != 0) {
for (String loop:data) {
int charSequenceSize = constraint.length();
if(onlyText(constraint.toString()) && !matchedResults.contains(loop)){
String[] split = loop.split(":");
String substring = split[0].substring(0, charSequenceSize);
if (substring.equalsIgnoreCase(constraint.toString())){
matchedResults.add(loop);
}
}else if(onlyNumbers(constraint.toString())){
String[] split = loop.split(":");
String substring = split[1].substring(0, charSequenceSize);
if (substring.equals(constraint.toString()) && !matchedResults.contains(loop) ){
matchedResults.add(loop);
}
}
}
}
results.values = matchedResults;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
results.values = matchedResults;
notifyDataSetChanged();
}
};
}
public boolean onlyText(String text) {
boolean result = false;
if (Pattern.matches("[a-zA-Z ]+", text) && text.length() >= 1) {
result = true;
}
return result;
}
public boolean onlyNumbers(String text) {
boolean result = false;
if (Pattern.matches("[0-9+]+", text) && text.length() >= 1) {
result = true;
}
return result;
}
}
update your filter to this
#Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
matchedResults.clear();
for (String item : data) {
if (item.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
matchedResults.add(item);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = matchedResults;
filterResults.count = matchedResults.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<String> filteredList = (ArrayList<String>) results.values;
if (results != null && results.count > 0) {
data.clear();
for (String c : filteredList) {
data.add(c);
}
notifyDataSetChanged();
}
}
};
So your entire code it be like this :
public class AutoCompleteAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<String> data;
private ArrayList<String> matchedResults = new ArrayList<String>();
public AutoCompleteAdapter(Context context, ArrayList<String> namesAndNumbers) {
this.context = context;
this.data = namesAndNumbers;
}
#Override
public int getCount() {
return matchedResults.size();
}
#Override
public String getItem(int position) {
return matchedResults.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_layout, parent, false);
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView numberTextView = (TextView) view.findViewById(R.id.number);
String[] split = matchedResults.get(position).split(":");
nameTextView.setText(split[0]);
numberTextView.setText(split[1]);
return view;
}
#Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
matchedResults.clear();
for (String item : data) {
if (item.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
matchedResults.add(item);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = matchedResults;
filterResults.count = matchedResults.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<String> filteredList = (ArrayList<String>) results.values;
if (results != null && results.count > 0) {
data.clear();
for (String c : filteredList) {
data.add(c);
}
notifyDataSetChanged();
}
}
};
public boolean onlyText(String text) {
boolean result = false;
if (Pattern.matches("[a-zA-Z ]+", text) && text.length() >= 1) {
result = true;
}
return result;
}
public boolean onlyNumbers(String text) {
boolean result = false;
if (Pattern.matches("[0-9+]+", text) && text.length() >= 1) {
result = true;
}
return result;
}
}
I hope to be helpful for you .