I follow this example to use autocmpletetextview in my project,i want to get id when user select any item,can anyone tell how to get id..
following is json response..so if click on ab then i want to get 1,if i click on abc i want to get 2..
MainActivity
public class MainActivity extends Activity {
private AutoCompleteTextView acTextView;
private String idtest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acTextView = (AutoCompleteTextView) findViewById(R.id.autoComplete);
final SuggestionAdapter adapter=new SuggestionAdapter(this, acTextView.getText().toString());
acTextView.setAdapter(adapter);
acTextView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
JsonParse jps=new JsonParse();
/* List<SuggestGetSet> list =jps.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.size();i++)
{
if(list.get(i).getName().equals(acTextView.getText().toString()))
idtest=list.get(position).getId();
}
*/
SuggestGetSet selectedSuggestGetSet =
adapter.getAllUpdatedSuggestion().get(position);
Toast.makeText(getApplicationContext(), selectedSuggestGetSet+acTextView.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
adapter
public class SuggestionAdapter extends ArrayAdapter<String> {
protected static final String TAG = "SuggestionAdapter";
public List<String> suggestions;
private List<SuggestGetSet> new_suggestions;
public SuggestionAdapter(Activity context, String nameFilter) {
super(context, android.R.layout.simple_dropdown_item_1line);
suggestions = new ArrayList<String>();
}
#Override
public int getCount() {
return suggestions.size();
}
#Override
public String getItem(int index) {
return suggestions.get(index);
}
#Override
public Filter getFilter() {
Filter myFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
JsonParse jp=new JsonParse();
if (constraint != null) {
// A class that queries a web API, parses the data and
// returns an ArrayList<GoEuroGetSet>
new_suggestions =jp.getParseJsonWCF(constraint.toString());
suggestions.clear();
for (int i=0;i<new_suggestions.size();i++) {
suggestions.add(new_suggestions.get(i).getName());
}
// Now assign the values and count to the FilterResults
// object
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
public List<SuggestGetSet> getAllUpdatedSuggestion(){
return this.new_suggestions;
}
}
response
{"results":[{"id":"1","name":"ab"},{"id":"2","name":"abc"},{"id":"3","name":"bc"},{"id":"4","name":"bcd"},{"id":"5","name":"cd"},{"id":"6","name":"cde"},{"id":"7","name":"ef"},{"id":"8","name":"efg"},{"id":"9","name":"hi"},{"id":"10","name":"hig"},{"id":"11","name":"jk"},{"id":"12","name":"jkl"},{"id":"13","name":"mn"},{"id":"14","name":"mno"},{"id":"15","name":"pq"},{"id":"16","name":"pqr"},{"id":"17","name":"st"},{"id":"18","name":"stu"},{"id":"19","name":"vw"},{"id":"20","name":"vwx"},{"id":"21","name":"yz"},{"id":"22","name":"yza"}]}
Put one method in adapter
public Int getItemId(int index) {
return suggestions.get(index).getId();
}
Then access it in onItemClick. You will getId from there by
adapter.getItemId(position);
How to get id of autocompletetextview item?
new_suggestions contains all items which want to get on ListView item click. so declare it outside getFilter method for access from other class:
private List<String> suggestions;
private List<SuggestGetSet> new_suggestions ;
....
new_suggestions initilize it inside getFilter method:
...
new_suggestions =jp.getParseJsonWCF(constraint.toString());
suggestions.clear();
...
Now create a method inside SuggestionAdapter :
public List<SuggestGetSet> getAllUpdatedSuggestion(){
return this.new_suggestions;
}
and finally inside onItemClick call getAllUpdatedSuggestion method:
final SuggestionAdapter adapter=new SuggestionAdapter(this,
acTextView.getText().toString())
acTextView.setAdapter(adapter);
and in onItemClick method:
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SuggestGetSet selectedSuggestGetSet =
adapter.getAllUpdatedSuggestion().get(position);
}
selectedSuggestGetSet will contains selected item name and id
Change your suggestions list to public :
public List<String> suggestions;
And then get the desired id in your itemClick method :
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
your id = YourAdapter.suggestions[position].id;
}
check this
List<SuggestGetSet> new_suggestions = jp.getParseJsonWCF(constraint.toString());
and make one with private List<SuggestGetSet> new_suggestions; in your adapter
Related
I have a custom ListView. It works fine except when attempting to filter a user search.
The code for displaying the ListView:
private void listShow() {
warranties=db.getAllServWarr();
adapter=new WarrantyAdapter(serviceswarranty_activity.this,warranties);
listView.setAdapter(adapter);
}
The code that implements the filter in the custom adapter:
public class WarrantyAdapter extends ArrayAdapter implements Filterable{
private ArrayList<ServicesWarranty> warrantyList;
private ArrayList<ServicesWarranty> filteredList;
private ItemFilter mFilter = new ItemFilter();
private Context context;
private int currPosition;
public WarrantyAdapter(#NonNull Context context,ArrayList<ServicesWarranty> warrantyList) {
super(context, R.layout.serviceswarranty_item,warrantyList);
this.warrantyList=warrantyList;
this.filteredList=warrantyList;
this.context=context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ServicesWarranty sw=warrantyList.get(position);
currPosition=position;
WarrantyAdapter.ViewHolder holder;
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.serviceswarranty_item,parent,false);
holder=new WarrantyAdapter.ViewHolder();
holder.lockno=(TextView)convertView.findViewById(R.id.lockNum_warrantyitem);
holder.fromdate=(TextView)convertView.findViewById(R.id.fromDate_warrantyItem);
holder.todate=(TextView)convertView.findViewById(R.id.toDate_warrantyItem);
holder.editIc=(ImageView)convertView.findViewById(R.id.editic_warrantyItem);
holder.deleteIc=(ImageView)convertView.findViewById(R.id.deleteic_warrantyItem);
convertView.setTag(holder);
}else{
holder=(WarrantyAdapter.ViewHolder) convertView.getTag();
}
holder.fill(sw);
return convertView;
}
private class ViewHolder{
public TextView lockno;
public TextView fromdate;
public TextView todate;
public ImageView editIc;
public ImageView deleteIc;
public void fill(final ServicesWarranty sw){
lockno.setText(String.valueOf(sw.getLockNumber()));
fromdate.setText(sw.getBeginDate());
todate.setText(sw.getEndDate());
editIc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(context,Add2warranty.class);
intent.putExtra("AddedWarrantyLockNo",sw.getLockNumber().toString());
context.startActivity(intent);
}
});
deleteIc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder deleteAlert=new AlertDialog.Builder(context);
deleteAlert.setMessage("آیا از حذف گارانتی با شماره قفل "+sw.getLockNumber().toString()+" اطمینان دارید؟")
.setPositiveButton("بله", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
AppDBHelper db=new AppDBHelper(context);
boolean res=db.deleteFromWarranty(sw.getID());
if(res) {
Toast.makeText(context, "Delete successfully", Toast.LENGTH_SHORT).show();
warrantyList.remove(currPosition);
notifyDataSetChanged();
}
}
})
.setNegativeButton("خیر",null)
.show();
}
});
}
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString();
FilterResults results = new FilterResults();
final List<ServicesWarranty> list = filteredList;
int count = list.size();
final ArrayList<ServicesWarranty> nlist = new ArrayList<ServicesWarranty>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i).getLockNumber().toString();
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(list.get(i));
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
warrantyList = (ArrayList<ServicesWarranty>) results.values;
notifyDataSetChanged();
}
}
}
and also i add this to my activity to enable search by filter
inputSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s.length()>0)
adapter.getFilter().filter(s);
return false;
}
});
When I debug this program, the adapter.getFilter().filter(s); works correctly, but near the end of function the program force closes.
Here is my logcat info
FATAL EXCEPTION: main
Process: com.example.zahra.prj1, PID: 18592
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
In my ListView, I have 2 items with values 13 and 14. I type 4 in search text box so the list size should be one.
Why is the filtering not working? Thanks for any help.
The problem is the array is out of bounds because getCount() is returning the size of the warrantyList instead of the filteredList.
There is a good example of how to handle the two lists here:
Implementing Filterable
But in general, the WarrantyAdapter should be using the filteredList. The ItemFilter should be using the warrantyList to publish the filteredList.
I have your code running in my environment with the following changes:
#Override
public int getCount() {
return filteredList.size();
}
#Override
public Object getItem(int position) {
return filteredList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
and I modified WarrantyAdapter to extend BaseAdapter and inside getView I use the filteredList...
I implemented an AutoCompleteTextView where the data is updated from the server every time the user enters a new text input. It works well. However, every time I enter a new query, the previous results are displayed until the new result set is updated.
My guess is that it displays the currently queried results until the backend responds with the new search results. Is there a way to clear the current results?
Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_test);
actv = (AutoCompleteTextView) findViewById(R.id.actv);
actv.setThreshold(1);
actv.setAdapter(new SearchSuggestionsAdapter(this, actv.getText().toString()));
Custom adapter:
public class SearchSuggestionsAdapter extends ArrayAdapter<String> {
List<String> types = new ArrayList<>();
protected static final String TAG = "SuggestionAdapter";
private List<String> suggestions;
private Context context;
public SearchSuggestionsAdapter(Activity context, String nameFilter) {
super(context, android.R.layout.simple_dropdown_item_1line);
suggestions = new ArrayList<String>();
this.context = context;
}
#Override
public int getCount() {
return suggestions.size();
}
#Override
public String getItem(int index) {
return suggestions.get(index);
}
#Override
public Filter getFilter() {
Filter myFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
//Get new results from backend
//searchItemsFromServer is the method that returns the data
//new data is successfully sent. no problem there
List<String> new_suggestions = searchItemsFromServer(constraint.toString());
suggestions.clear();
for (int i = 0; i < new_suggestions.size(); i++) {
suggestions.add(new_suggestions.get(i));
}
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence contraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
Thank you in advance!
Change your code to your activity to this
SearchSuggestionsAdapter searchSuggestionsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_test);
searchSuggestionsAdapter = new SearchSuggestionsAdapter(this, actv.getText().toString());
actv = (AutoCompleteTextView) findViewById(R.id.actv);
actv.setThreshold(1);
actv.setAdapter(searchSuggestionsAdapter);
actv.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
searchSuggestionsAdapter.clear();
}
}
});
}
Add the following code to your SearchSuggestionsAdapter
/**
* Create list and notify recycler view
*/
public void clear() {
if (suggestions != null) {
suggestions.clear();
notifyDataSetChanged();
}
}
actv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
suggestionAdapter.clear;
}
});
When user click on autocomplete remove the old adapter. But for this you need to define suggesstionAdapter first. and every time update this adapter and set it to autocomplete
Clear suggestion before filtering. Call adapter.clear();
Add new method in adapter
public void clear() {
suggestions.clear();
notifyDataSetChanged();
}
I have custom listview using simple adapter, Currently I have issue regarding filter that I have custom list data with numbers and characters in listview.
If I enter name then its give one blank space the filter results gets disappear.
I have list data like name then number for example : NAME 123, Whenever I enter name then gives space in that edit text then results are gone and list-view gets disappears.
I have tried this on below link but they used Array adapter, So my question is is it possible only in Array adapter or I can used simple adapter?
Android listview edittext filter space button?
If yes then how can I implement, kindly help. Advance thank you.
try this way
searchView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
return true;
}
});
addTextChangeListener();
now create method addTextChangeListener
private void addTextChangeListener() {
searchView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().trim().toLowerCase();
final ArrayList<CityDataModel> filteredList = new ArrayList<>();
final CharSequence finalQuery = query;
new Thread(new Runnable() {
#Override
public void run() {
// Clear the filter list
filteredList.clear();
// If there is no search value, then add all original list items to filter list
if (TextUtils.isEmpty(finalQuery)) {
filteredList.addAll(cities);
} else {
// Iterate in the original List and add it to filter list...
for (CityDataModel item : cities) {
if (item.getCity_name().toLowerCase().contains(finalQuery.toString().toLowerCase())
) {
// Adding Matched items
filteredList.add(item);
}
}
}
// Set on UI Thread
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
// Notify the List that the DataSet has changed...
adapter = new SearchCityAdapter(SearchCityClass.this, filteredList);
recyclerSearchCity.setAdapter(adapter);
}
});
}
}).start();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
You can use any Adapter, you can just implements your adapter with android.widget.Filterable
Example Adapter,
public class AppAdapter extends RecyclerView.Adapter<AppHolder> implements Filterable {
public static final String TAG = AppAdapter.class.getSimpleName();
private ArrayList<App> mApps = new ArrayList<>();
private List<App> mCurrentItmCopy = new ArrayList<>();
private String currentFilter;
private MyArrayFilter mFilter;
#Override
public AppHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View receiverView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.layout_row_apps, parent, false);
return new AppHolder(receiverView);
}
#Override
public void onBindViewHolder(final AppHolder holder, int position) {
final App data = mApps.get(position);
}
#Override
public int getItemCount() {
return mApps.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyArrayFilter();
}
return mFilter;
}
private class MyArrayFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mCurrentItmCopy == null || (mCurrentItmCopy.size() == 0)) {
mCurrentItmCopy = new ArrayList<App>(mApps);
}
ArrayList<App> newValues = new ArrayList<App>();
if (prefix != null && !TextUtils.isEmpty(prefix.toString())) {
String prefixString = prefix.toString().toLowerCase();
for (App value : mCurrentItmCopy) {
String label = value.getLabel().toLowerCase();
if ((label.contains(prefixString)) && !newValues.contains(value)) {
newValues.add(value);
}
}
results.values = newValues;
results.count = newValues.size();
} else {
results.values = new ArrayList<App>(mCurrentItmCopy);
results.count = mCurrentItmCopy.size();
mCurrentItmCopy.clear();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
currentFilter = constraint.toString();
if (results.count > 0) {
mApps.clear();
addAll((ArrayList<App>) results.values);
} else {
mApps.clear();
notifyDataSetChanged();
}
}
}
public void addAll(List<App> items) {
if (items != null) {
mApps.addAll(items);
}
notifyDataSetChanged();
}
}
In the above Adapter instead of App, you can use your object.
You can call from your activity or fragment like this,
mAdapter.getFilter().filter(newText);
I try added filter to ArrayList (data is from json/php script on my server). I find but I not see resolving...
I try more sample codes and more resolving, but nothing works.
listView = (ListView) findViewById(R.id.list);
list = new ArrayList<FriendItem>();
adapter = new FriendAllAdapter(context, list);
listView.setAdapter(adapter);
String filename = getResources().getString(R.string.friendalllist_php);
asyncLoadVolley = new AsyncLoadVolley(context, filename);
Map<String, String> map = new HashMap<String, String>();
map.put(Constant.ID, Sessions.getUserId(context));
asyncLoadVolley.setBasicNameValuePair(map);
asyncLoadVolley.setOnAsyncTaskListener(asyncTaskListener);
connectionDetector = new ConnectionDetector(context);
if(savedInstanceState==null) {
}
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(listItemClickListener);
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
//here added filter...
}
});
For example:
You have a model - FriendItem
public class FriendItem {
private String firstName;
private String lastName;
//.....
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
and have an adapter - FriendAllAdapter.
In this adapter you should implement Filterable interface.
You"ll need to Override getFilter() method and return new object of Filter class (android.widget.Filter).
In performFiltering() method your need return FilterResults object with count of filtered elements and value - list of elements. Also in this method you need to realize the algorithm comparison of the search query to values in your FriendItem (list item). In my example I search FriendItem(s) which fields (firstName or lastName) contains text in my editText.
Input parameter is a CharSequence object which you set in onTextChanged() method on added textChangeListener to your EditText.
myFilter.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
});
In publishResults() method your get filtering result your need cast results.values to List and replace your list to filtering result.
public class FriendAllAdapter extends BaseAdapter implements Filterable {
private List<FriendItem> list;
private final List<FriendItem> fullList = new ArrayList<>();
public FriendAllAdapter(Context context, List<FriendItem> list) {
//...... your code
this.list = list;
fullList.addAll(list);
}
//...... your code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//... your code
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) { // if your editText field is empty, return full list of FriendItem
results.count = fullList.size();
results.values = fullList;
} else {
List<FriendItem> filteredList = new ArrayList<>();
constraint = constraint.toString().toLowerCase(); // if we ignore case
for (FriendItem item : fullList) {
String firstName = item.getFirstName().toLowerCase(); // if we ignore case
String lastName = item.getLastName().toLowerCase(); // if we ignore case
if (firstName.contains(constraint.toString()) || lastName.contains(constraint.toString())) {
filteredList.add(item); // added item witch contains our text in EditText
}
}
results.count = filteredList.size(); // set count of filtered list
results.values = filteredList; // set filtered list
}
return results; // return our filtered list
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
list = (List<FriendItem>) results.values; // replace list to filtered list
notifyDataSetChanged(); // refresh adapter
}
};
return filter;
}
}
I think you`ll understand it.
P.S. sorry for my English.
i'm try to write simple filtering ListView by this below code. but that does not work correctly
in this code i'm using ContactListStructure class structure as:
public class ContactListStructure implements Serializable {
public Long id;
public String name;
public String mobile;
public Bitmap photo;
public Boolean checked;
...
}
and i'm fill this class as an ArrayList with phone contacts. after fill that i'm set this list into ListView without any problem,then i'm try to fillter this list by:
/* private ArrayList<ContactListStructure> contact_item; */
contactsAdapter = new ContactsAdapter ( G.contact_item , ActivityContactList.this);
lstContent.setAdapter ( contactsAdapter );
search_contacts.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
contactsAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
POST UPDATE
search_contacts is an EditText and after type into that ListView dont filter and dont any change. my BaseAdapter :
public class ContactsAdapter extends BaseAdapter implements Filterable {
private Context mCtx=null;
private ArrayList<ContactListStructure> mData=null;
private ArrayList<ContactListStructure> arraylist;
private List<ContactListStructure> worldpopulationlist = null;
private ItemFilter mFilter = new ItemFilter();
static int i=0;
public ContactsAdapter (ArrayList<ContactListStructure> contact_item, Context ctx) {
mData=contact_item;
mCtx=ctx;
this.worldpopulationlist = contact_item;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public ContactListStructure getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null) {
LayoutInflater inflator=((Activity)mCtx).getLayoutInflater();
convertView=inflator.inflate(R.layout.send_sms,null);
}
CheckBox chk_name_mobile = (CheckBox)convertView.findViewById(R.id.chk_name_mobile);
ImageView photo = (ImageView)convertView.findViewById(R.id.photo);
String name=mData.get(position).name;
chk_name_mobile.setText(name);
if( mData.get(position).photo == null )
photo.setImageDrawable( G.context.getResources().getDrawable(R.drawable.user) );
else
photo.setImageBitmap(mData.get(position).photo);
return convertView;
}
#Override
public Filter getFilter () {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString();
FilterResults results = new FilterResults();
final ArrayList<ContactListStructure> list = mData;
int count = list.size();
final ArrayList<ContactListStructure> nlist = new ArrayList<ContactListStructure>(count);
String filterableString ;
for (ContactListStructure wp : worldpopulationlist)
{
if (wp.getName().contains(filterString))
{
//Log.e ("wp: ", String.valueOf ( wp ) );
ContactListStructure item = new ContactListStructure();
item.id = wp.id;
item.name = wp.name;
item.mobile = wp.mobile;
item.photo = wp.photo;
nlist.add(item);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arraylist = (ArrayList<ContactListStructure>) results.values;
notifyDataSetChanged();
}
}
}
UPDATE POST:
after help in comments my notifyDataSetChanged not working. after type into edit text thats can be find but listview dont refresh.
You can try following this question here: ListView is blank while using getFilter function
It was able to filter based on a choice from the ListView.
I think you forgot to add the data returned from result to your mData :
protected void publishResults(CharSequence constraint, FilterResults results) {
arraylist = (ArrayList<ContactListStructure>) results.values;
mData.clear();
for(int i = 0, i < arraylist.size(); i++)
mData.add(arraylist.get(i));
notifyDataSetChanged();
}
}