Android autocompletetextview to have two adapter for suggestion - android

I have a problem in making suggestion in AutoCompleteTextView in this pattern
[action actionFromContact] (these are 2 adapter) ex call michael (where "call" comes from action adapter , "michael" from actionFromContact adapter these following code does first it set adapter in AutoCompleteTextView to item and when text changes to call it reset to contact db from name so its like call michael ,
Problem item array is too big so I can't use replace thing , second replacing remove the first entry when second entry i.e name is been selected from drop down menu as its been replaced by space
private AutoCompleteTextView mEditText;
private TextWatcher mTextWatcher;
private ContactPickerAdapter contactPickerAdapter;
String item[] = { "Call", "Call back"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (WithSomeOneAutoCompleteTextView) findViewById(R.id.editTextTest);
contactPickerAdapter = new ContactPickerAdapter(this,
android.R.layout.simple_dropdown_item_1line,
ContactQuery.getContacts(this, false));
mEditText.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, item));
mTextWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
String t = s.toString().replace("call ",");
contactPickerAdapter.getFilter().filter(t);
if (s.toString().equalsIgnoreCase("call ")) {
Toast.makeText(MainActivity.this, "CALL",
Toast.LENGTH_SHORT).show();
mEditText.setAdapter(contactPickerAdapter);
}
if (s.toString().equalsIgnoreCase("Call back")) {
// t.replace("call back ", "");
// System.out.println("t is: " + t);
// contactPickerAdapter.getFilter().filter(t);
Toast.makeText(MainActivity.this, "Launch",
Toast.LENGTH_SHORT).show();
}
}
};
}
This is ContactPickerAdapter
public class ContactPickerAdapter extends ArrayAdapter<Contact> implements
Filterable {
private ArrayList<Contact> contactList, cloneContactList;
private LayoutInflater layoutInflater;
private Context mContext;
public ContactPickerAdapter(Context context, int textViewResourceId,
ArrayList<Contact> contactList) {
super(context, textViewResourceId);
this.contactList = contactList;
this.cloneContactList = (ArrayList<Contact>) this.contactList.clone();
layoutInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return contactList.size();
}
#Override
public Contact getItem(int position) {
return contactList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.withsomeone_contact_list_item, null);
holder = new Holder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.phone = (TextView) convertView.findViewById(R.id.phone);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
Contact contact = getItem(position);
holder.name.setText(contact.contactName);
holder.phone.setText(contact.num);
return convertView;
}
#Override
public Filter getFilter() {
Filter contactFilter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results.values != null) {
contactList = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// CharSequence t = "";
System.out.println("contraints is equal: " + constraint);
// if (constraint.toString().contains("call ")) {
// // constraint = "";
// System.out.println("contraints now: "
// + constraint.toString().replace("call ", ""));
// t = constraint.toString().replace("call ", "");
// }
// } else if
// (constraint.toString().equalsIgnoreCase("call back ")) {
// // constraint = "";
// System.out.println("contraints now: " + constraint);
// t = constraint.toString().replace("call back ", "");
//
// }
// System.out.println("clone is equal: " + t);
String sortValue = constraint == null ? "" : constraint
.toString().toLowerCase();
FilterResults filterResults = new FilterResults();
if (!TextUtils.isEmpty(sortValue.trim())) {
ArrayList<Contact> sortedContactList = new ArrayList<Contact>();
for (Contact contact : cloneContactList) {
if (contact.contactName.toLowerCase().contains(
sortValue)
|| contact.num.toLowerCase()
.contains(sortValue))
sortedContactList.add(contact);
}
filterResults.values = sortedContactList;
filterResults.count = sortedContactList.size();
}
return filterResults;
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// need to save this to saved contact
return ((Contact) resultValue).contactName;
}
};
return contactFilter;
}
#SuppressWarnings("unchecked")
public void setContactList(ArrayList<Contact> contactList) {
// this isn't the efficient method
// need to improvise on this
this.contactList = contactList;
this.cloneContactList = (ArrayList<Contact>) this.contactList.clone();
notifyDataSetChanged();
}
public static class Holder {
public TextView phone, name;
}

Still a bit unclear what are you trying to achieve.
Anyway.
Well as a first step I would attach the TextWatcher to the mEditText
mEditText.addTextChangedListener(mTextWatcher);
Then I would remove
contactPickerAdapter.getFilter().filter(t);
see how it goes.
I suggest that you post the code of your contactPickerAdapter as well.

Related

Listview Id Changes

I have read through the forums and I can't seem to figure out how to get the position of the selected item to match my array list items since the listview is searchable. It works great until I search then my items do not match up. Can someone provide an exact example?
private void displayListView() {
ArrayList<Country> countryList = new ArrayList<Country>();
//countryList.clear();
// int j=1;
for (int i = 0; i < categoriesList.size(); i++) {
//list.add(new ItemData(categoriesList.get(i).getName(), R.drawable.ic_launcher));
//Array list of countries
Country country = new Country(workordertypeId.get(i),ActualCity.get(i),ClientName.get(i),
ProjectNotes.get(i), ProjectStart.get(i),ProjectFieldNotes.get(i),ProjectStatus.get(i));
countryList.add(country);
///////list.add(new StringWithTag(categoriesList.get(i).getName(),categoriesList2.get(i).getName()));
//list.add(new ItemData("testthis",R.drawable.logolong4));
}
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,
R.layout.country_info, countryList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
//listView.has
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
setwoindex(position);
//setwoindex (parent.getSelectedItemPosition());
//listView.getItemId(position)
Country country = (Country) parent.getItemAtPosition(position);
//Toast.makeText(getApplicationContext(),
//country.getCode(), Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(),
//country.getRegion(), Toast.LENGTH_SHORT).show();
String haspdf = getIntent().getExtras().getString("haspdf", "defaultKey");
if (haspdf.equals("1")) {
//counter++;
btnAddNewCategory.setText("Save PDF");
btnAddNewCategory.setEnabled(true);
} else if (haspdf.equals("0")) {
btnAddNewCategory.setEnabled(false);
}
if (haspdf.equals("3")) {
//counter++;
btnAddNewCategory.setText("Save Image");
btnAddNewCategory.setEnabled(true);
} else if (haspdf.equals("0")) {
btnAddNewCategory.setEnabled(false);
}
//updateGUI();
//Toast.makeText(getBaseContext(), "test", Toast.LENGTH_SHORT).show();
//spinnerFood.setTag(pos);
if (getwoindex() != null) {
// punchin.setEnabled(true);
Viewattachments.setEnabled(true);
//punchin.setEnabled(true);
// punchout.setEnabled(true);
//btnAddNewCategory.setEnabled(true);
int index = getwoindex();
//Toast.makeText(getBaseContext(),"WorkOrderNumber Toasting="+ workordertypeId.get(index).toString() +" "+ClientName.get(index).toString()+" "+ActualCity.get(index).toString()+" "+ClientPhone.get(index).toString(), Toast.LENGTH_SHORT).show();
FullAddress.setText(WoClientName.get(index).toString() + "\n" + WoClientStreet.get(index).toString() + "\n" + ActualCity.get(index).toString() + " " + WoClientState.get(index).toString() + " " + WoClientZip.get(index).toString());
ActualPhone.setText(WoClientPhone.get(index).toString());
String IdUser = getIntent().getStringExtra("IdUser");
String usernameforlogin = getIntent().getStringExtra("usernameforlogin");
mrcastrovinci();
}
}
});
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) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
private CountryFilter filter;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public android.widget.Filter getFilter() {
if (filter == null){
filter = new CountryFilter();
}
return filter;
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
TextView Dated;
TextView ProjectFieldNotes;
TextView ProjectStatus;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
holder.Dated = (TextView) convertView.findViewById(R.id.dated);
holder.ProjectFieldNotes = (TextView) convertView.findViewById(R.id.ProjectFieldNotes);
holder.ProjectStatus = (TextView) convertView.findViewById(R.id.ProjectStatus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
holder.Dated.setText(country.getDated());
holder.ProjectFieldNotes.setText(country.getProjectFieldNotes());
holder.ProjectStatus.setText(country.getProjectStatus());
return convertView;
}
private class CountryFilter extends android.widget.Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<Country> filteredItems = new ArrayList<Country>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
Country country = originalList.get(i);
if(country.toString().toLowerCase().contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
//setwoindex(ListView1.getSelectedItemPosition());
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}
Would it be acceptable to extend the Country object to contain an id/index?
If yes, that would be stored all the way and you could retrieve it back in the onItemClick for you ListView.
If not, you could build a wrapper around the Country object and either feed that to the adapter or have the adapter construct a list of wrappers.
public class MyWrapper {
public Country mCountry;
public int mOriginalIndex;
}
Yes I actually just extended my country list and included all my items there. I will add an index Id also.

Android Custom Adapter Filter not working

I am using a custom adapter with a search filter in a fragment, however the results don't get filtered on a search, I debugged and stepped through my code and find that it is saying that the args.listenere = null!. What does this mean and how do I correct it? My code is below:
---------Custom Adapter -------
public class SalesPartAdapter extends BaseAdapter implements Filterable {
private ArrayList<SalesPartItem> listData;
private ArrayList<SalesPartItem> filteredData;
private SalesPartFilter filter;
private Context _context;
private LayoutInflater layoutInflater;
public SalesPartAdapter(Context context, ArrayList<SalesPartItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
_context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
//set background colour
if (convertView == null) {
//set up holder
convertView = layoutInflater.inflate(R.layout.salespart_item, null);
holder = new ViewHolder();
holder.salesPartCodeView = (TextView) convertView.findViewById(R.id.salesPartCode);
holder.salesPartDescView = (TextView) convertView.findViewById(R.id.salesPartDescription);
holder.salesPartColourBar= (ImageView) convertView.findViewById(R.id.colourBar);
convertView.setTag(holder);
} else {
//use existing holder
holder = (ViewHolder) convertView.getTag();
}
SalesPartItem salespartView = (SalesPartItem) listData.get(position);
holder.salesPartCodeView.setText(salespartView.SalesPartCode);
holder.salesPartDescView.setText(salespartView.SalesPartDescription);
holder.salesPartColourBar.setBackgroundColor(Color.parseColor(salespartView.Colour));//String.valueOf(salespartView.Colour);
return convertView;
}
/********* holder Class to contain previously inflated xml file elements *********/
static class ViewHolder {
TextView salesPartCodeView;
TextView salesPartDescView;
ImageView salesPartColourBar;
}
public Filter getFilter() {
if (filter == null){
filter = new SalesPartFilter();
}
return filter;
}
ArrayList<SalesPartItem> filteredItems;
ArrayList<Integer>countFilteredItems;
private class SalesPartFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
filteredItems = new ArrayList<SalesPartItem>();
// countFilteredItems = new ArrayList<Integer>();
for(int i = 0, l = listData.size(); i < l; i++)
{
SalesPartItem salesPartItem = listData.get(i);
if(salesPartItem.SalesPartDescription.toString().toLowerCase().contains(constraint))
filteredItems.add(salesPartItem);
// countFilteredItems.add(i);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = listData;
result.count = listData.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// notifyDataSetChanged();
if (results.count > 0) {
listData =(ArrayList<SalesPartItem>)results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
----------------Fragment code that deals with the list view -------------------
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//USE SAMPLE ID TO GET SALES PARTS LIST FROM DATABASE
addSalesParts.setEnabled(false);
//ListViewModel (SalesPartId,salesPartName,NotUsed)
final int numberOfAddedSalesParts = 3;
SalesPartItem sp;
// fill with some dummy data for now.
for (long i = 1; i < numberOfAddedSalesParts; i++) {
sp = new SalesPartItem();
sp.SalesPartItemId = i;
sp.SalesPartCode = "LEU" + i;
if(i!=2){
sp.SalesPartDescription = "Sales Part " + i;
}
else{
sp.SalesPartDescription = "TSalZes Part " + i;
}
sp.Colour = "#cccccc";
salesPartListViewItems.add(sp);
}
// Start of Search filtering
mListView = (ListView) getActivity().findViewById(R.id.salespartsList);
//click on item - edit order
mListView.setTextFilterEnabled(true);
//display the list via our custom adapter
mListView.setAdapter(new SalesPartAdapter(getActivity(), salesPartListViewItems);
EditText searchField = (EditText) getActivity().findViewById(R.id.typeFindSalesPart);
searchField.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//TODO Search Lists from Database and filter accordingly
SalesPartAdapter SA = new SalesPartAdapter(getActivity(), salesPartListViewItems);
SA.getFilter().filter(s.toString());
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
// salesPartListViewItems.contains(s);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
I have now resolved this, the issue was that I was creating a new instance of the adapter in the text watcher. Once I set it to use the adapter that created the original list then it worked fine

Using an EditText to search through a ListView

I'm trying to search through a ListView With the use of a TextView, after writing the code, it was Logging out what I did, but not filtering the List I want it to filter. Here is my code:
public class LabDetailActivity extends ActionBarActivity {
private LabAdapter labListAdapter;
private List<LabItem> labItem;
private TextView searchText;
private SearchView mSearchView;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assigned_lab_fragments);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Labs");
searchText = (TextView) findViewById(R.id.labText);
list = (ListView) findViewById(android.R.id.list);
labItem = new ArrayList<LabItem>();
labListAdapter = new LabAdapter(this, labItem);
list.setAdapter(labListAdapter);
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new ListItemClickListener());
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
/*labListAdapter.getFilter().filter(charSequence.toString());
list.setAdapter(labListAdapter);*/
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
int textLength = charSequence.length();
List<LabItem> labItemss = new ArrayList<LabItem>();
for (LabItem ll : labItem){
if(textLength <= ll.getName().length()){
if (ll.getName().toLowerCase().contains(charSequence.toString().toLowerCase())){
labItemss.add(ll);
}
}
}
Log.d("SIZE OF SEARCH", String.valueOf(labItemss.size()));
labListAdapter = new LabAdapter(LabDetailActivity.this, labItemss);
list.setAdapter(labListAdapter);
}
#Override
public void afterTextChanged(Editable editable) {
/*Log.d("NEW TAGS", "*** Search value changed: " + editable.toString());
if (editable.toString().length() >= 3)
labListAdapter.getFilter().filter(editable.toString());*/
//labListAdapter.getFilter().filter(editable.toString());
//labListAdapter.notifyDataSetChanged();
}
});
}
private class ListItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
}
private void RetrieveData(){
Uri uri2 = Uri.parse("content://" + getString(R.string.LEONE_AUTHORITY) + "/olabs");
Log.d("URL PRINT", uri2.toString());
final Cursor cursor = getContentResolver().query(uri2, null, null, null, "_id");
Log.d("CURSOR DATA:", cursor.toString());
JSONArray array = new JSONArray();
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
JSONObject object = new JSONObject();
try {
object.put("lab_number", cursor.getString(cursor.getColumnIndex("lab_case_number")));
object.put("lab_name", cursor.getString(cursor.getColumnIndex("lab_case_name")));
array.put(object);
Log.d("ARRAY", String.valueOf(array.length()));
} catch (JSONException e) {
e.printStackTrace();
}
}
parseJsonLabs(array);
cursor.close();
}
}
private void parseJsonLabs(JSONArray array){
Log.d("CASESARRAY", array.toString());
try {
labItem.clear();
for (int i = 0; i < array.length(); i++) {
JSONObject cases = (JSONObject) array.get(i);
LabItem items = new LabItem();
items.setName(cases.getString("lab_number"));
items.setCase(cases.getString("lab_name"));
labItem.add(items);
}
labListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO: handle exception
Log.e("ARRAYTEST", "ERROR:", e);
}
}
#Override
protected void onResume() {
super.onResume();
RetrieveData();
}
}
Then, the Adapter code is here
Adapter
public class LabAdapter extends BaseAdapter implements Filterable{
private Activity activity;
private LayoutInflater inflater;
private List<LabItem> labItem;
private TextView labName, labCase;
public LabAdapter(Activity activity, List<LabItem> labItem){
this.activity = activity;
this.labItem = labItem;
}
#Override
public int getCount() {
return labItem.size();
}
#Override
public Object getItem(int position) {
return labItem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.custom_lab_activity_list, null);
labName = (TextView) convertView.findViewById(R.id.custom_lab_name);
labCase = (TextView) convertView.findViewById(R.id.custom_lab_case);
LabItem labs = labItem.get(position);
labName.setText(labs.getName());
labCase.setText(labs.getCase());
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
Log.d("SEARCHTEXT2", "**** PERFORM FILTERING for: " + charSequence);
charSequence = charSequence.toString().toLowerCase();
FilterResults filts = new FilterResults();
if (charSequence == null || charSequence.length() == 0){
filts.values = labItem;
filts.count = labItem.size();
} else {
// We perform filtering operation
List<LabItem> labrs = new ArrayList<LabItem>();
for (LabItem l : labrs){
if (l.getName().startsWith(charSequence.toString()) || l.getCase().startsWith(charSequence.toString()))
labItem.add(l);
}
filts.values = labItem;
filts.count = labItem.size();
//filts.count = labItem.size();
}
return filts;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
// Now we have to inform the adapter about the new list filtered
Log.d("SEARCHTEXT1", "**** PUBLISHING RESULTS for: " + charSequence);
if (filterResults.count == 0)
notifyDataSetInvalidated();
else {
labItem = (List<LabItem>) filterResults.values;
notifyDataSetChanged();
}
}
};
}
public void notifyDataSetChanged(){
super.notifyDataSetChanged();
}
}
And the Item class is here
Item Class
public class LabItem {
String labCase, labName;
public LabItem() {
}
public LabItem(String labCase, String labName){
super();
this.labCase = labCase;
this.labName = labName;
}
public String getName(){
return labName;
}
public void setName(String name){
this.labName = name;
}
public String getCase(){
return labCase;
}
public void setCase(String cases){
this.labCase = cases;
}
}
I don't know if I'm not updating the ListView very well or something. When I type a i see the count, but If I add another letter. The LIST would be gone. Any help would be appreciated. Thanks in advance.
Few Logical Mistakes : I got here this code working at my end
public LabAdapter(Activity activity, List<LabItem> labItem){
this.activity = activity;
this.labItem = labItem;
}
#Override
public int getCount() {
return labItem.size();
}
#Override
public LabItem getItem(int position) { //instead of Object make it Labitem
return labItem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.activity_stack, null);
labName = (TextView) convertView.findViewById(R.id.textView1);
labCase = (TextView) convertView.findViewById(R.id.textView2);
LabItem labs = labItem.get(position);
labName.setText(labs.getName());
labCase.setText(labs.getCase());
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
Log.d("SEARCHTEXT2", "**** PERFORM FILTERING for: " + charSequence);
charSequence = charSequence.toString().toLowerCase();
FilterResults filts = new FilterResults();
if (charSequence == null || charSequence.length() == 0){
filts.values = labItem;
filts.count = labItem.size();
} else {
// We perform filtering operation
List<LabItem> labrs = new ArrayList<LabItem>();
for (LabItem l : labItem){ //you are going to search in labItem that contains the data and not the empty list labrs
if (l.getName().startsWith(charSequence.toString()) || l.getCase().startsWith(charSequence.toString())){
Log.e("(l.getName().startsWith(charSequence.toString())","" + charSequence);
labrs.add(l); // add to the new list**
}
}
filts.values = labrs; //set values to the new list**
filts.count = labrs.size();
//filts.count = labItem.size();
}
return filts;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
// Now we have to inform the adapter about the new list filtered
Log.d("SEARCHTEXT1", "**** PUBLISHING RESULTS for: " + charSequence);
List<LabItem> filtered = (List<LabItem>) filterResults.values;
labItem = filtered; // set the new data as you want with the new set you've received.**
notifyDataSetChanged();
}
};
}
public void notifyDataSetInvalidated()
{
super.notifyDataSetInvalidated();
}
then in your LabDetailActivity.class change it as
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
labListAdapter.getFilter().filter(charSequence.toString());
Log.d("NEW TAGS", "*** Search value changed: " + labListAdapter.getCount());
list.invalidate();
labListAdapter.notifyDataSetChanged();
list.setAdapter(labListAdapter);
}
Edit:
P.S. This code is still not perfect as after clearing the text it
doesn't sets the list back. I leave it to you. Hope this solves your
problem you've been facing.
Let me know if it works.

Filter listview with custom layout?

So I have a basic custom listview with an image and text for each list item and I was wondering how I would filter through the listview dynamically with an edittext box. I looked up how to do it but I'm stuck at one point where I'm not sure what to do.
My listview is populated from an sqlitedatabase where I have methods that retrieve all the images names, text and ids from the database and puts them into the listview. Here is my code so far where I'm not quite sure what I should be doing in the publishResult() method
public class MainActivity extends Activity {
ListView data;
EditText inputSearch;
ArrayList<String> names, images, ids;
ArrayAdapter<String> adapter;
MyDatabase helper;
ImageView sprite;
TextView name, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = (ListView) findViewById(R.id.listView1);
helper = new MyDatabase(this);
helper.openDataBase();
names = helper.getNameList();
images = helper.getImageList();
ids = helper.getIdList();
adapter = new MyArrayAdapter(this);
data.setAdapter(adapter);
inputSearch = (EditText) findViewById(R.id.edit_search);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
private class MyArrayAdapter extends ArrayAdapter<String>{
public MyArrayAdapter(Context c) {
super(c, R.layout.item_view,names);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (convertView == null){
row = getLayoutInflater().inflate(R.layout.item_view, parent,false);
}
sprite = (ImageView) row.findViewById(R.id.sprite);
name = (TextView) row.findViewById(R.id.name);
id = (TextView) row.findViewById(R.id.ids);
name.setText(names.get(position).toString());
int resID = getResources().getIdentifier(images.get(position),"drawable", getPackageName());
sprite.setImageResource(resID);
id.setText(ids.get(position).toString());
return row;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return new Filter(){
#Override
protected FilterResults performFiltering(CharSequence input) {
FilterResults results = new FilterResults();
int originalLength = names.size();
if (input == null || input.length() == 0){
results.values = names;
results.count = originalLength;
} else {
ArrayList<String> newList = new ArrayList<String>();
for (int i = 0; i < originalLength; i++){
String str = names.get(i);
if (str.toLowerCase(Locale.getDefault()).contains(input))
newList.add(str);
results.values = newList;
results.count = newList.size();
}
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence,
FilterResults results) {
//Not sure what to do here
notifyDataSetChanged();
}
};
}
}
Try this , I think it help you.
#Override
protected void publishResults(CharSequence charSequence,
FilterResults results) {
if(results.count==0)
{
notifyDataSetInvalidated();
}else
{
names=(ArrayList<String> names)results.values;
notifyDataSetChanged();
}
}
Thanks
Should be pretty simple at that point...
Edit:
public class FakeAdapter extends ArrayAdapter<Model> {
public class Model {
String my_string;
int resource_id;
}
private Activity activity;
/* ArrayList to hold the original values before filtering. */
private ArrayList<Model> original_list;
/* Current Data Filter */
private Filter filter;
public RelationshipsAdapter(Activity activity, int resource,
ArrayList<Model> objects) {
super(activity, resource, objects);
this.activity = activity;
this.original_list = objects;
}
/**
* Viewholder pattern to minimize findViewById calls.
*/
private static class ViewHolder {
TextView name;
ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Model currentmodel = getItem(position);
View rowView = null;
if(convertView == null){
rowView = activity.getLayoutInflater().inflate(R.layout.my_item, parent, false);
final ViewHolder holder = new ViewHolder();
holder.name = (TextView) rowView.findViewById(R.id.item_text);
holder.image = (ImageView) rowView.findViewById(R.id.item_image);
rowView.setTag(holder);
} else {
rowView = convertView;
}
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.name.setText(currentmodel.my_string);
holder.friendship.setImageResource(currentmodel.resource_id);
return rowView;
};
/**
* Returns a filter to the calling activity to filter the underlying data set by name.
*/
#Override
public Filter getFilter(){
if(filter == null){
filter = new ModelFilter();
}
return filter;
}
/** Custom Filter implementation used to filter names alphabetically on a provided prefix. */
private class ModelFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence search) {
FilterResults filter_results = new FilterResults();
String prefix = search.toString();
/* If the search is empty, display the original dataset. */
if(UserInputValidation.checkText(prefix).equals(StatusCode.NULL_INPUT)){
filter_results.values = original_list;
filter_results.count = original_list.size();
} else {
//make a copy of the original items and use that array list
final ArrayList<RelationshipModel> results = new ArrayList<RelationshipModel>(original_list);
final ArrayList<RelationshipModel> results_holder = new ArrayList<RelationshipModel>();
int count = results.size();
for(int i = 0; i < count; i++){
final RelationshipModel model = results.get(i);
final String name = (model.first_name + " " + model.last_name).toLowerCase(Locale.US);
if(name.contains(prefix))
results_holder.add(model);
}
filter_results.values = results_holder;
filter_results.count = results_holder.size();
}
return filter_results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
clear();
addAll((ArrayList<RelationshipModel>) results.values);
}
}
}

Filter ListView with arrayadapter

I'm trying to filter a listview with arrayadapter. The arraydapter parameter is a String[][]. The problem is that anything happens. I must override the Filter interface? In that case plase, can someone provide some hints?
Every position of the array I'm trying to filter is like
galleryValues[0][0] -> "tiulo"
[0][1] -> "desc"
[0][2] -> "etc"
I tryied to filter it:
lstContinente = (ListView)findViewById(R.id.list);
lstContinente.setTextFilterEnabled(true);
adapter = new PortaitArrayAdapter(cx,galleryValues);
lstContinente.setAdapter(adapter);
ed_busqueda.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
}
});
The adapter code:
public class PortaitArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[][] values;
private List<Imagen> imagenes = null;
private LayoutInflater mInflater;
public ImageLoader imageLoader;
public PortaitArrayAdapter(Context context, String[][] values) {
super(context, R.layout.gallery_row);
this.context = context;
this.values = values;
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imagenes = new ArrayList<Imagen>();
for (int i = 0; i < 20; i++) imagenes.add(new Imagen());
Bitmap def = BitmapFactory.decodeResource(this.context.getResources(),R.drawable.ic_launcher);
imageLoader=new ImageLoader(this.context,def, imagenes);
}
#Override
public int getCount (){
return this.values.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.gallery_row, parent, false);
holder.txtTitulo = (TextView) convertView.findViewById(R.id.txt_gallery_titulo);
holder.txtDesc = (TextView) convertView.findViewById(R.id.txt_gallery_desc);
holder.txtFecha = (TextView) convertView.findViewById(R.id.txt_gallery_fecha);
holder.txtEst = (TextView) convertView.findViewById(R.id.txt_gallery_est);
holder.imageView = (ImageView)convertView.findViewById(R.id.lst_img_gallery);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
/*LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.gallery_row, parent, false);*/
//ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
Bitmap bmp;
Log.v("Position --> ",String.valueOf(position));
try {
byte b[] = imagenes.get(position).getImageData();
if (b != null) {
bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
if (bmp != null) holder.imageView.setImageBitmap(bmp);
} else {
String urlBase = galleryValues[position][0].substring(0, galleryValues[position][0].lastIndexOf("/")+1);
String urlToEncode = galleryValues[position][0].substring(galleryValues[position][0].lastIndexOf("/")+1, galleryValues[position][0].length());
urlToEncode = URLEncoder.encode(urlToEncode,"UTF-8");
String url = urlBase.concat(urlToEncode);
url = url.replace("+", "%20");
Log.v("UrlFinal --> ",url);
imageLoader.DisplayImage(String.valueOf(position),url,act,holder.imageView, position,null);
}
} catch (Exception e) {
Log.e(this.getClass().getName(),"Exception en pos = " + position + " error:" + e.getMessage());
e.printStackTrace();
}
holder.txtTitulo.setText(galleryValues[position][1] + ", " + galleryValues[position][2]);
String[] dates = galleryValues[position][4].split("/");
String date = dates [1] + "/" + dates[0] + "/" + dates[2];
Date d1 = new Date(date);
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
holder.txtDesc.setText(galleryValues[position][3]);
holder.txtFecha.setText(df.format(d1));
holder.txtEst.setText(getText(R.string.num_fotos_gallery) + galleryValues[position][5] + " - " + getText(R.string.num_videos_gallery) + galleryValues[position][6] + " - " + getText(R.string.num_exp_gallery) + galleryValues[position][7]);
return convertView;
}
}
private static class ViewHolder {
TextView txtTitulo;
TextView txtDesc;
TextView txtFecha;
TextView txtEst;
ImageView imageView;
}
Convert your String array to ArrayList and pass it to Adapter and use below code or change below code with your String[].
You need to implement Filterable to your Adapter class and Override getFilter()
Checkout this complete example for filtering custom Adapter.
public class ListFilterActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
List<String> mOriginalValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyAdapter adapter = new MyAdapter(this, getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
// Add Text Change Listener to EditText
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<String> getModel() {
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("iPhone");
list.add("Windows XP");
return list;
}
}
// Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<String> arrayList;
List<String> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<String> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(arrayList.get(position));
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
arrayList = (List<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
Here I mention the code of how We can filter the listView Data using custom Adapter
Its really help you
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
public List<AllFoodItem> allFoodItemlist;
public ArrayList<AllFoodItem> arraylist;
public ListViewAdapter(Context context, List<AllFoodItem> allFoodItemlist) {
mContext = context;
this.allFoodItemlist = allFoodItemlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AllFoodItem>();
this.arraylist.addAll(allFoodItemlist);
}
#Override
public int getCount() {
return allFoodItemlist.size();
}
#Override
public AllFoodItem getItem(int position) {
return allFoodItemlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView foodname, quantity, calorie;
}
public View getView(final int position, View view, ViewGroup parent) {
Holder holder = new Holder();
view = inflater.inflate(R.layout.program_list, null);
// Locate the TextViews in listview_item.xml
holder.foodname = (TextView) view.findViewById(R.id.textView1);
// Set the results into TextViews holder.foodname.setText(allFoodItemlist.get(position).getName().toString());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
allFoodItemlist.clear();
if (charText.length() == 0) {
allFoodItemlist.addAll(arraylist);
} else {
for (AllFoodItem wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
allFoodItemlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
MainActivity.java
use the ListViewAdapter class apply filter on EditText by using filter() method
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
foodname = (inputSearch.getText().toString()).trim();
// filter the data of edit Text using filter method in ListViewAdapter
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
userGet();
// TODO Auto-generated method stub
}
});

Categories

Resources