can someone please give me an link of filling AutoCompleteTextView using BaseAdapter in android for phone contacts.
Thanks
user750716 is wrong.
You can fill AutoCompleteTextView with BaseAdapter. You just need to remember that BaseAdapter has to implement Filterable.
In Adapter create your ArrayList of Objects.
Implement getView with whatever View you want and fill it with objects.get(position) info.
Implement getItem(int position) returning a string (name of clicked object)
In the same adapter add stuff for filtering:
public Filter getFilter() {
return new MyFilter();
}
private class MyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence filterString) {
// this will be done in different thread
// so you could even download this data from internet
FilterResults results = new FilterResults();
ArrayList<myObject> allMatching = new ArrayList<myObject>()
// find all matching objects here and add
// them to allMatching, use filterString.
results.values = allMatching;
results.count = allMatching.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
objects.clear();
ArrayList<myObject> allMatching = (ArrayList<myObject>) results.values;
if (allMatching != null && !allMatching.isEmpty()) {
objects = allMatching;
}
notifyDataSetChanged();
}
}
This is not possible with an BaseAdapter but you can use a CursorAdapter with no SQLite DB in the background. In the function runQueryOnBackgroundThread you can create an MatrixCursor.
Something like this:
String[] tableCols = new String[] { "_id", "keyword" };
MatrixCursor cursor = new MatrixCursor(tableCols);
cursor.addRow(new Object[] { 1, "went" });
cursor.addRow(new Object[] { 2, "gone" });
I have done this in my morphological analyzer.
Related
I have an listview with filter. When I input some words in an edittext that I used as a filter for example "david", it works well, items in the list are filtered and it will show all item that contains "david". But when I delete some words, for example "dav", the list is still filtered, but it filtered from the last filtered by "david".
Let's say I had 40 items, filtered by "david", it becomes 24 items. Then I filtered it again with "dav", it filtered from the "24 items" one, not the "40 items" one.
Here is my custom adapter:
public class WRegistrantListAdapter extends ArrayAdapter<Registrant> {
private Context mContext;
private int mResource;
private List<Registrant> mOriginalList;
private List<Registrant> mFilteredList;
public WRegistrantListAdapter(Context context, int resource, ArrayList<Registrant> oobjects, int workshopItemId) {
super(context, resource, oobjects);
mContext = context;
mResource = resource;
mFilteredList = oobjects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//contains code for displaying item.
}
#NonNull
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults result = new FilterResults();
String constraint = charSequence.toString().toLowerCase();
if (mOriginalList == null) {
mOriginalList = mFilteredList;
Toast.makeText(mContext, String.valueOf(mOriginalList.size()), Toast.LENGTH_SHORT).show();
}
if (constraint == null || constraint.isEmpty() || constraint.equals("")) {
result.values = mOriginalList;
result.count = mOriginalList.size();
} else {
List<Registrant> list = new ArrayList<>();
int max = mOriginalList.size();
for (int cont = 0; cont < max; cont++) {
Registrant item = mOriginalList.get(cont);
boolean contains =
item.getRegistrantName().toLowerCase().contains(constraint) ||
item.getRegistrantNumber().toLowerCase().contains(constraint);
if (contains) {
list.add(mOriginalList.get(cont));
}
}
result.values = list;
result.count = list.size();
}
return result;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
clear();
addAll((ArrayList<Registrant>) results.values);
notifyDataSetChanged();
}
};
}
}
Which part in the filtering is wrong? Any help would be much appreciated. Hope my explanation is not confusing because English is not my mother language.
You need two different lists for filtering, so try change mOriginalList = mFilteredList; to mOriginalList = new ArrayList<>(mFilteredList); may solve the issue.
Explanations:
mOriginalList = mFilteredList; is same list with two different names. It is helpful in modular program, just like mFilteredList = oobjects; in your adapter constructor.
mOriginalList = new ArrayList<>(mFilteredList); is to make a shallow copy of mFilteredList and store it as mOriginalList, so the lists are different.
Shallow and Deep Copy:
Example: If your custom class, Registrant, contains a public field (List, Map or custom object etc., that requires new for creation) named sample. Under shallow copy, mOriginalList = new ArrayList<>(mFilteredList);, mOriginalList.get(i) is a copy of mFilteredList.get(i) and they are 2 different Registrant objects. But mOriginalList.get(i).sample and mFilteredList.get(i).sample is the same object.
If you need mOriginalList.get(i).sample and mFilteredList.get(i).sample to be different objects, then it is called deep copy. There is no ready method to make deep copy, you have to make your own method according to your custom class. But up to now, I never have a case that needs deep copy.
Hope that helps!
You should keep two separate lists in your adapter such as,
private List<Registrant> mOriginalList = new ArrayList();
private List<Registrant> mFilteredList = new ArrayList();
public WRegistrantListAdapter(Context context, int resource, ArrayList<Registrant> oobjects, int workshopItemId) {
super(context, resource, oobjects);
mContext = context;
mResource = resource;
mFilteredList.addAll(oobjects);
mOriginalList.addAll(oobjects);
}
Initially, both of them should have the same value and you will use filteredList for showing your data. Later in the filter, you should publish your data like
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList.clear();
filteredList.addAll((ArrayList<Registrant>) results.values);
notifyDataSetChanged();
}
A complete example is can be found in Filter ListView with arrayadapter
I am using an ArrayAdapter with filterable interface to implement search functionality in a listview.My code for adapter is following:
public class FlightsAdapter extends ArrayAdapter<Flight> implements Filterable {
List<Flight> flightLists = new ArrayList<Flight>();
private List<Flight> origFlightList;
private Context context;
Flight flight = null;
public FlightsAdapter(Context context, int textViewResourceId,
List<Flight> fLists) {
super(context, textViewResourceId, fLists);
this.context = context;
this.flightLists = fLists;
}
public void updateFlightList(List<Flight> newData){
this.flightLists.clear();
this.flightLists = newData;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final List<Flight> results = new ArrayList<Flight>();
if (origFlightList == null)
origFlightList = flightLists;
if (constraint != null) {
if (origFlightList != null && origFlightList.size() > 0) {
for (final Flight f : origFlightList) {
if (f.getPlace().toLowerCase()
.contains(constraint.toString()))
results.add(f);
}
}
oReturn.values = results;
oReturn.count = results.size();
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
flightLists = (ArrayList<Flight>) results.values;
notifyDataSetChanged();
}
};
}
}
getFilter() and publishResults() methods get triggered properly on searching and flightLists get populated with new data but the listview remain same with no items change, I don't know what I am doing wrong in above code, Please help me figure out this problem
Here is the problem
flightLists = (ArrayList<Flight>) results.values;
Replace this with
flightLists.clear();
flightLists.addAll((ArrayList<Flight>) results.values);
See if that fixes your issue.
Later edit (explanation):
When you created your adapter, you gave it a List object. The adapter thus has a reference, a pointer, to that List, from where it takes the data to display.
When you have replaced that reference with a whole other block of memory
flightLists = (ArrayList<Flight>) results.values;
the adapter didn't updated the orignial data set (from where it actually was taking data to display). Thus, notifyDataSetChanged() didn't work.
When updating the data in an adapter, you have to keep the original data structure reference intact. Clearing and populating with another data set is an option. Reinstantiating it (in any way) isn't.
This is basic java.
It seems that this should be easy.
I have an Android app with a list using an ArrayAdapter. It works. I replace the ArrayAdapter with a custom sub-class. It works. I add a inner class that is a sub-class of Filter and mark the ArrayAdaptor sub-class as implementing Fiterable. And it works fine, except that it does not filter.
What is the magic word I have to say here?
None of the methods in the Filter sub-class are being invoked.
public class XYZListAdapter extends ArrayAdapter<XYZListFragment.XYZItem> implements Filterable {
private List<XYZListFragment.XYZItem> sourceObjects;
private Context sourceContext;
private XYZFilter xyzFilter;
public XYZListAdapter(Context context, int resource, int textViewResourceId, List<XYZListFragment.XYZItem> objects) {
super(context, resource, textViewResourceId, objects);
sourceObjects = new ArrayList<>(objects);
sourceContext = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("XYZAdapter", "getView");
View v = convertView;
if (v == null) {
v = ((LayoutInflater)sourceContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.fragment_xyz_list_item, parent, false);
}
XYZListFragment.XYZItem mItem = sourceObjects.get(position);
if (mItem != null) {
TextView t = (TextView)v.findViewById(R.id.xyz_list_item_name_view);
if (t != null) {
t.setText(mItem.name());
}
}
return v;
}
#Override
public Filter getFilter() {
Log.i("XYZAdapter", "getFilter");
if (xyzFilter == null)
xyzFilter = new XYZFilter();
return xyzFilter;
}
private class XYZFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
Log.i("XYZFilter", "perform");
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
results.values = sourceObjects;
results.count = sourceObjects.size();
}
else {
List<XYZListFragment.XYZItem> nextXYZList = new ArrayList<>();
for (XYZListFragment.XYZItem p : sourceObjects) {
if (p.name().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nextXYZList.add(p);
}
results.values = nextXYZList;
results.count = nextXYZList.size();
}
return results;
}
#Override
#SuppressWarnings("unchecked")
protected void publishResults(CharSequence constraint, FilterResults results) {
Log.i("XYZFilter", "publish");
if (results.count == 0)
notifyDataSetInvalidated();
else {
sourceObjects = (List<XYZListFragment.XYZItem>) results.values;
notifyDataSetChanged();
}
}
}
}
It doesn't work because you shouldn't subclass the ArrayAdapter if you want to customize it's filtering logic. You would need to implement an adapter from scratch using the BaseAdapter.
Basically, the ArrayAdapter internally tracks its own list of objects. However you are only updating your list of objects in the subclass. You need to update the internal list as well. Otherwise the adapter is not aware of the change.
There are other issues. For instance, the performFiltering() method executes on a background thread. That means you need to synchronize any changes done to the list. The ArrayAdapter already does this internally...and you have no way of accessing the sync lock object it uses...which makes it impossible for you to safely sync.
Also, your filtering solution doesn't seem to provide a solution for restoring the list back to its original state after the filtering is cleared out.
You can read more about the problems with ArrayAdapter filtering here. General rule of thumb. When using the ArrayAdapter don't create your own list to track the data and don't customize the filtering. Optionally, you can use something like the AbsArrayAdapter which is just like an ArrayAdapter but lets you define the filtering logic for you.
Good day,
I have a following problem. In my Android application I have a list of entries in XML that contains bus stop name and ID. Those are put in a HashMap as IDs are unique, while stop names are not. The user interface of activity contains an AutoCompleteTextView and Spinner.
My objective is to populate auto-complete view with stop names and then pass the ID of selected stop to the other class that will display bus lines on that stop in spinner (via remote API).
So what the user will do is start typing stop name (e.g. Awesome Stop) and he will see two entries in auto-complete suggestions. Depending on which one he will select spinner will show different results.
My problem is that I can't figure out how to couple AutoCompleteTextView and HashMap. Auto-complete works well with ArrayAdapter<String> populated via ArrayList<String> but it's not terribly helpful because I can only get stop name back, and it's not very helpful since I actually need ID.
Many thanks for any tip.
OK, after a fair bit of time I figured it out, thanks to the tip from joaquin. It was indeed done by implementing custom adapter. And the HashMap was not very helpful in original goal. Below is the code, if someone stumbles upon a similar challenge.
Activity:
// Members
private long currentStopId;
protected Map<String,String> lineMap;
protected ArrayList<Stop> stopMap;
protected String previousUrl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_line);
// Get the list of stops from resourse XML
getStopInformation();
// Enable auto-complete
stopInput = (AutoCompleteTextView) findViewById(R.id.inputStopName);
final HashMapAdapter adapter = new HashMapAdapter(this,R.layout.stop_list,stopMap);
stopInput.setAdapter(adapter);
// Add listener for auto-complete selection
stopInput.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String)parent.getItemAtPosition(position);
// There we get the ID.
currentStopId = parent.getItemIdAtPosition(position);
}
});
}
Adapter implementation:
public class StopAdapter extends BaseAdapter implements Filterable {
private ArrayList<Stop> inputStopList;
private ArrayList<Stop> inputStopListClone;
private LayoutInflater lInflater;
/** Constructor */
public StopAdapter(Context context, int textViewResourceId, ArrayList<Stop> input) {
lInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inputStopList = input;
inputStopListClone = inputStopList;
}
#Override
public int getCount() {
return inputStopList.size();
}
#Override
public Object getItem(int i) {
Stop value = inputStopList.get(i);
return value.getStopName();
}
#Override
public long getItemId(int i) {
Stop stop = inputStopList.get(i);
long value = Long.parseLong(stop.getStopCode());
return value;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View myView = view;
// R.layout.stop_list created in res/layout
if(myView == null)
myView = lInflater.inflate(R.layout.stop_list,viewGroup, false);
((TextView) myView.findViewById(R.id.textView)).setText(getItem(i).toString());
return myView;
}
/** Required by AutoCompleteTextView to filter suggestions. */
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
if(charSequence == null || charSequence.length() == 0) {
ArrayList<Stop> originalValues = new ArrayList<Stop>(inputStopList);
filterResults.count = originalValues.size();
filterResults.values = originalValues;
}
else {
ArrayList<Stop> newValues = new ArrayList<Stop>();
// Note the clone - original list gets stripped
for(Stop stop : inputStopListClone)
{
String lowercase = stop.getStopName().toLowerCase();
if(lowercase.startsWith(charSequence.toString().toLowerCase()))
newValues.add(stop);
}
filterResults.count = newValues.size();
filterResults.values = newValues;
}
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if(filterResults != null && filterResults.count > 0) {
inputStopList = (ArrayList<Stop>)filterResults.values;
notifyDataSetChanged();
}
else notifyDataSetInvalidated();
}
};
return filter;
}
}
You are using AutoCompleteTextView instead of MultiAutoCompleteTextView.
MultiAutoCompleteTextView is exactly what you need because it works exactly equal as AutoCompleteTextView with the difference that it can show more than one suggestion (if they exist) and lets the user choose only one of them.
Reference Image: http://i.stack.imgur.com/9wMAv.png
For a nice example check out Android Developers: http://developer.android.com/reference/android/widget/MultiAutoCompleteTextView.html
I have AutoCompleteTextView attached to my view, and used ArrayAdapter to populate for list of items. But I am unaware of how to add header and footer view for AutocompleteTextView drop down's item.
I know we can add header and footer in listview.
Any suggestions ?
On an AutoCompleteTextView, you don't have direct access to the DropDownListView, that's why you cannot add header and footer views there.
A solution to your problem will be to use 2 types of views in your list, and set the first/last row to have the header's/footer's layout. This can be done on the adapter, which you create yourself.
Here's some info about how to provide different layouts for different rows in a list view:
Android ListView with different layouts for each row
Android provided methods like addHeaderView(View v) and addFooterView(View v) to define headers and footers for the ListViews.
To find an answer on your question, I can refer you to Android: Adding static header to the top of a ListActivity.
Good luck!
private class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}};
return filter;
}
}
where autocomplete function should return the arraylist of string