Search Filter is not working - android

Nothing happening even i am entering exact "key" name in EditText whereas it has to be show only that record in a list.
Filtering is not working, this is how my JSON looks like:
{
"data": [
{
"id": "1",
"name": "Era Locksmith",
"key": "EraLoc2015"
},
{
"id": "2",
"name": "Mac Garage Door",
"key": "MacGdr2015"
}
]
}
I am extending ArrayAdapter<....> and implementing Filterable
CompanyListAdapter.java:
public class CompanyListAdapter extends ArrayAdapter<Company> implements Filterable {
private Context context;
ArrayList<Company> products;
SharedPreference sharedPreference;
private ArrayList<Company> filteredCompanies;
private CompanyFilter mFilter = new CompanyFilter();
public CompanyListAdapter(Context context, ArrayList<Company> products) {
super(context, R.layout.company_list_item, products);
this.context = context;
this.products = products;
sharedPreference = new SharedPreference();
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ViewHolder {
TextView productNameTxt;
TextView productKeyTxt;
ImageView favoriteImg;
}
#Override
public int getCount() {
return products.size();
}
#Override
public Company getItem(int position) {
return products.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.company_list_item, null);
holder = new ViewHolder();
holder.productNameTxt = (TextView) convertView
.findViewById(R.id.txt_pdt_name);
holder.productKeyTxt = (TextView) convertView
.findViewById(R.id.txt_pdt_price);
holder.favoriteImg = (ImageView) convertView
.findViewById(R.id.imgbtn_favorite);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Company product = (Company) getItem(position);
holder.productNameTxt.setText(product.getName());
holder.productKeyTxt.setText(product.getPrice() + "");
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(product)) {
holder.favoriteImg.setImageResource(R.drawable.heart_red);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.heart_grey);
holder.favoriteImg.setTag("grey");
}
return convertView;
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Company checkProduct) {
boolean check = false;
List<Company> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (Company product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(Company product) {
super.add(product);
products.add(product);
notifyDataSetChanged();
}
#Override
public void remove(Company product) {
super.remove(product);
products.remove(product);
notifyDataSetChanged();
}
private class CompanyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<Company> list = products;
int count = list.size();
final ArrayList<Company> nlist = new ArrayList<Company>(count);
Company filterableCompany;
for (int i = 0; i < count; i++) {
filterableCompany = list.get(i);
if (filterableCompany.getKey().toLowerCase().contains(filterString)) {
nlist.add(filterableCompany);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredCompanies = (ArrayList<Company>) results.values;
notifyDataSetChanged();
}
}
}
Using EditText to accept "key"
CompanyListActivity.java:
EditText filterList = (EditText) view.findViewById(R.id.editKey);
filterList.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
productListAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
I am using code provided by #Leigh

Why not use implement Filterable?
Try something like this:
Make your adapter class look like this:
public class CompanyListAdapter extends ArrayAdapter<Company> implements Filterable {
private List<Company> companies;
private List<Company> filteredCompanies;
private CompanyFilter mFilter = new CompanyFilter();
private Context context;
SharedPreference sharedPreference;
public CompanyListAdapter(Context context, ArrayList<Company> products) {
super(context, R.layout.company_list_item, products);
this.context = context;
this.products = products;
this.filteredCompanies = products;
sharedPreference = new SharedPreference();
}
#Override
public int getCount() {
return filteredCompanies == null 0 : filteredCompanies.size();
}
#Override
public Company getItem(int position) {
return filteredCompanies.get(position);
}
#Override
public Filter getFilter() {
return mFilter;
}
}
Next go ahead and create a CompanyFilter:
private class CompanyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<Company> list = companies;
int count = list.size();
final ArrayList<Company> nlist = new ArrayList<Company>(count);
Company filterableCompany;
for (int i = 0; i < count; i++) {
filterableCompany = list.get(i);
if (filterableCompany.getName().toLowerCase().contains(filterString)) {
nlist.add(filterableCompany);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredCompanies = (ArrayList<Company>) results.values;
notifyDataSetChanged();
}
}
This way you get to apply your filter to any number of fields. Note I am using the getName() of the company class to apply the filter in my example.
EDIT:
TO use this in an Activity / Fragment for searching you can add a TextWatcher to your EditText and apply the filter onTextChanged. Something like this:
txtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
});

you need to make your adapter implement Filterable like this:
class CustomAdapter extends BaseAdapter implements Filterable {
#Override
public Filter getFilter() { ...}
try to look at this answer:
List View Filter Android

Related

ArrayAdapter Custom filter not working

I have a problem with my custom filter. I make it, and it works well. When I debug code, it filtrates array well, but I have a problem in void publishResults(). I don't know what is a problem, anyone helps?
public class KatalogAdapter extends ArrayAdapter<Katalog> implements Filterable {
List<Katalog> object;
int num = 0;
public KatalogAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List<Katalog> objects) {
super(context, resource, objects);
object = objects;
}
public void setObject(List<Katalog> kat){
this.object = kat;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.katalozi_item, null);
}
Katalog katalog = object.get(position);
ImageView katalogImage = (ImageView) v.findViewById(R.id.katalogImage);
TextView katalogProizvodjac = (TextView) v.findViewById(R.id.katalogProizvodjac);
TextView katalogVaziDo = (TextView) v.findViewById(R.id.katalogVaziDo);
TextView idKataloga = (TextView) v.findViewById(R.id.idKataloga);
String src = katalog.getImageSRC();
Picasso.with(getContext()).load(src).into(katalogImage);
/*Glide.with(getContext()).load(src).thumbnail(Glide.with(getContext()).load(R.drawable.loading_icon))
.fitCenter()
.crossFade().into(katalogImage); */
// katalogImage.setImageBitmap(bitmap);
katalogProizvodjac.setText(katalog.getKatalogProizvodjac());
String doe = katalog.getKatalogVaziDo();
char lastChar = doe.charAt(doe.length() - 1);
if(lastChar=='1'){
katalogVaziDo.setText("Važi još "+ doe +" dan");
}
if(doe.equals("0")){
katalogVaziDo.setText("Važi još danas");
}
if(lastChar!='1' && !doe.equals("0")){
katalogVaziDo.setText("Važi još "+katalog.getKatalogVaziDo() + " dana");
}
// katalogVaziDo.setText("Važi do: "+katalog.getKatalogVaziDo());
idKataloga.setText(String.valueOf(katalog.getIdKataloga()));
return v;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
ArrayList<Katalog> tempList=new ArrayList<Katalog>();
//constraint is the result from text you want to filter against.
//objects is your data set you will filter from
if(constraint != null && object!=null) {
int length=object.size();
int i=0;
while(i<length){
Katalog item=object.get(i);
if(item.getKatalogProizvodjac().toLowerCase(Locale.getDefault()).contains(constraint.toString().toLowerCase())){
tempList.add(item);
}
i++;
}
//following two lines is very important
//as publish result can only take FilterResults objects
filterResults.values = tempList;
filterResults.count = tempList.size();
}
return filterResults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// object = (ArrayList<Katalog>) results.values;
setObject((List<Katalog>) results.values);
num = results.count;
notifyDataSetChanged();
}
};
}
}
I was looking for an answer, and I found that in that function I need to put in array my data. I did it, but still not work.
i am provide recyler view adapter with filter for contact details and you can change code your need according.
public class InviteContactAdapter extends RecyclerView.Adapter<InviteContactAdapter.ItemViewHolder> implements Filterable {
private List<UserContact> mContactList = new ArrayList<>();
private List<UserContact> mContectFilter = new ArrayList<>();
private Context mContext;
private CustomFilter mFilter;
public List<String> mEmailList = new ArrayList<>();
public InviteContactAdapter(Context context, List<UserContact> mContactList) {
mContext = context;
this.mContactList = mContactList;
this.mContectFilter = mContactList;
mFilter = new CustomFilter();
}
public onItemClickListener onItemClickListener;
public void setOnItemClickListener(InviteContactAdapter.onItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.invite_contact_row_layout, viewGroup, false);
return new ItemViewHolder(view);
}
public interface onItemClickListener {
void onClick(UserContact contact);
}
#Override
public Filter getFilter() {
return mFilter;
}
#Override
public void onBindViewHolder(final ItemViewHolder itemViewHolder, int i) {
final UserContact contact = mContectFilter.get(i);
itemViewHolder.mTvUserNane.setText(contact.getUserName().trim());
itemViewHolder.mTvUserEmail.setText(contact.getUserEmail().trim());
if (contact.isSelect())
itemViewHolder.mIvSelect.setImageResource(R.drawable.check_contect);
else
itemViewHolder.mIvSelect.setImageResource(R.drawable.un_check_contact);
itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (contact.isSelect()) {
contact.setSelect(false);
itemViewHolder.mIvSelect.setImageResource(R.drawable.un_check_contact);
} else {
contact.setSelect(true);
itemViewHolder.mIvSelect.setImageResource(R.drawable.check_contect);
}
}
});
}
#Override
public int getItemCount() {
return mContectFilter.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView mTvUserNane, mTvUserEmail;
private ImageView mIvSelect;
public ItemViewHolder(View itemView) {
super(itemView);
mTvUserEmail = itemView.findViewById(R.id.icrlTvUserEmail);
mTvUserNane = itemView.findViewById(R.id.icrlTvUserName);
mIvSelect = itemView.findViewById(R.id.icrlIvSelect);
}
}
public List<String> getEmail() {
mEmailList.clear();
for (UserContact contact : mContectFilter) {
if (contact.isSelect()) {
mEmailList.add(contact.getUserEmail());
}
}
return mEmailList;
}
/**
* this class for filter data.
*/
class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
if (charSequence != null && charSequence.length() > 0) {
ArrayList<UserContact> filters = new ArrayList<>();
charSequence = charSequence.toString().toUpperCase();
for (int i = 0; i < mContactList.size(); i++) {
if (mContactList.get(i).getUserName().toUpperCase().contains(charSequence) || mContactList.get(i).getUserEmail().toUpperCase().contains(charSequence)) {
UserContact contact = new UserContact();
contact.setUserName(mContactList.get(i).getUserName());
contact.setUserEmail(mContactList.get(i).getUserEmail());
filters.add(contact);
}
}
results.count = filters.size();
results.values = filters;
} else {
results.count = mContactList.size();
results.values = mContactList;
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mContectFilter = (ArrayList<UserContact>) filterResults.values;
notifyDataSetChanged();
}
}
}
and call into activity in edittext box for filter record like below ..
filter the data
Note: make sure your adapter object not null
/**
* this method filter data.
*/
private void sortData(View root) {
mEtSearchData = (EditText) root.findViewById(R.id.icffEtSearch);
mEtSearchData.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) {
if (inviteContactAdapter != null) {
inviteContactAdapter.getFilter().filter(s);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
My problem was that in some line I hade gridView.setAdapter(null).
However, I had one more problem, in gridView I had 5 elements, after filtering, I had one item filled with real data and 4 more empty items.. So, I changed getView function..
If someone need it, here it is:
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.katalozi_item, null);
}
if(objectfilt.size()>position){
Katalog katalog = objectfilt.get(position);
ImageView katalogImage = (ImageView) v.findViewById(R.id.katalogImage);
TextView katalogProizvodjac = (TextView) v.findViewById(R.id.katalogProizvodjac);
TextView katalogVaziDo = (TextView) v.findViewById(R.id.katalogVaziDo);
TextView idKataloga = (TextView) v.findViewById(R.id.idKataloga);
String src = katalog.getImageSRC();
Picasso.with(getContext()).load(src).into(katalogImage);
/*Glide.with(getContext()).load(src).thumbnail(Glide.with(getContext()).load(R.drawable.loading_icon))
.fitCenter()
.crossFade().into(katalogImage); */
// katalogImage.setImageBitmap(bitmap);
katalogProizvodjac.setText(katalog.getKatalogProizvodjac());
String doe = katalog.getKatalogVaziDo();
char lastChar = doe.charAt(doe.length() - 1);
if(lastChar=='1'){
katalogVaziDo.setText("Važi još "+ doe +" dan");
}
if(doe.equals("0")){
katalogVaziDo.setText("Važi još danas");
}
if(lastChar!='1' && !doe.equals("0")){
katalogVaziDo.setText("Važi još "+katalog.getKatalogVaziDo() + " dana");
}
// katalogVaziDo.setText("Važi do: "+katalog.getKatalogVaziDo());
idKataloga.setText(String.valueOf(katalog.getIdKataloga()));
return v;
}
else {
v.setVisibility(View.GONE);
return v;
}
So, elements from ListArray objectfilt are added, and when int position become bigger than number of ListView elements, then just hide that views.

Android ListView does not refresh by Filter

In my application I have three fragment with ViewPager. one of this fragments i have simple Arraylist as ListView from phones contact list and i'm trying to filter that after typing into edittext.
but doesn't refresh until softkeyboard is visible and I must have to hide keyboard to refresh list view by filtered strings.
For example:
filter listview by "a":
adapter.getFilter().filter("a");
My adapter:
public class AdapterContacts extends BaseAdapter implements Filterable {
private LayoutInflater inflater;
private Context context;
private List<ContactLists> categoryArrayList;
private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
private NameFilter filter;
public AdapterContacts(ArrayList<ContactLists> array) {
categoryArrayList = array;
}
public AdapterContacts(Context context, List<ContactLists> array) {
this.context = context;
inflater = LayoutInflater.from(this.context);
categoryArrayList = array;
originalList.addAll(array);
}
#Override
public int getCount() {
return categoryArrayList.size();
}
#Override
public ContactLists getItem(int position) {
return categoryArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_contacts_list_item, null);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
ContactLists item = getItem(position);
mViewHolder.fillItems(this, item, position);
return convertView;
}
private static class UI extends HelperUI {
public TextView tv_person_nickname_mobile_number;
public TextView btn_invite_message;
public ImageView img_contact_image;
public ImageView imgv_user_rank;
public TextView tv_contact_name;
public LinearLayout ll_root;
public UI(View view) {
parseUi(view);
}
}
private class ViewHolder {
private UI UI;
public ViewHolder(View view) {
UI = new UI(view);
}
public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
UI.tv_contact_name.setText(item.getContact_name());
if (item.getStatus() == 1) {
UI.btn_invite_message.setVisibility(View.GONE);
UI.imgv_user_rank.setVisibility(View.VISIBLE);
if (item.getRank() != null || !TextUtils.isEmpty(item.getRank())) {
//Picasso.with(G.context).load(item.getRank()).into(UI.imgv_user_rank);
}
UI.tv_person_nickname_mobile_number.setText(item.getNick_name());
//UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_button_actions));
if (item.getContact_image() == null || TextUtils.isEmpty(item.getContact_image())) {
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
} else {
// show user avatar from web
//Picasso.with(G.context).load(item.getContact_image()).into(UI.img_contact_image);
UI.img_contact_image.setImageBitmap(BitmapFactory.decodeFile(G.dir_image + "/" + item.getContact_image()));
}
} else {
// UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_invite_actions));
UI.btn_invite_message.setVisibility(View.VISIBLE);
UI.imgv_user_rank.setVisibility(View.GONE);
UI.btn_invite_message.setText(UC.getString(R.string.invite_person));
UI.btn_invite_message.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.shape_invite_button_default));
UI.tv_person_nickname_mobile_number.setText(item.getMobile_number());
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new NameFilter();
}
return filter;
}
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
}
softkeyboard status status in Manifest for ActivityMain. this class have view pager with three fragment:
<activity android:name=".Activities.ActivityBootstrap" android:windowSoftInputMode="adjustPan" android:screenOrientation="portrait"/>
other way to do Filter in fragment without Adapter's ability
edt_sample.addTextChangedListener(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 text = edt_sample.getText().toString();
filter(text);
}
});
public void filter(String charText) {
drinks.clear();
if (charText.length() == 0) {
drinks.addAll(contact_list);
} else {
for (ContactLists wp : contact_list) {
if (wp.getContact_name().contains(charText)) {
drinks.add(wp);
}
}
}
contact_list.clear();
contact_list.addAll(drinks);
adapter.notifyDataSetChanged();
}
ListView succesful filtered by when i close or hide softkeyboard that refresh with nw items.
You're not making use of your adapter filter as I see from the code posted by you. I'll post here an example filter and how to call it (kept all your variable names to make it easier).
The 'NameFilter' class, inside your adapter class:
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
The 'TextWatcher' interface method implementation in your list fragment:
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
String text = searchView.getText().toString();
NameFilter itemFilter = (NameFilter) adapter.getFilter();
itemFilter.filter(text);
}
Also, some observations:
if 'ContactLists' is a contact, name it 'Contact', to avoid confusion
I would use a 'SearchView', instead of an 'EditText'
I don't know how you get the contact list, but there's a guide about it here (if you didn't look at it already)
It is very simple to implement. Please follow these below steps:
Step 1:
Initialize Edittext:
editTextVideoFolderSearch = (EditText) rootView.findViewById(R.id.editTextVideoFolderSearch);
Step 2:
Add TextChangedListener on this edittext. like:
editTextVideoFolderSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence t, int start, int before,
int count) {
videoDetailBeansSearch.clear();
for (int i = 0; i < videoDetailBeans_total.size(); i++) {
if (videoDetailBeans_total.get(i).getAlbum().toLowerCase()
.contains(t)) {
videoDetailBeansSearch.add(videoDetailBeans_total.get(i));
}
}
if (videoDetailBeansSearch.size() > 0) {
video_folder_gridView.setAdapter(new AlbumGridAdapter(getActivity(), videoDetailBeansSearch));
} else {
video_folder_gridView.setAdapter(new AlbumGridAdapter(getActivity(), videoDetailBeansSearch));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Step 3: you have to make different beans for populating the adapter in list view:
private ArrayList<MediaDetailBean> videoDetailBeansSearch = new ArrayList<MediaDetailBean>();
private ArrayList<MediaDetailBean> videoDetailBeans_total = new ArrayList<MediaDetailBean>();
private ArrayList<MediaDetailBean> videoDetailBeans_delete = new ArrayList<MediaDetailBean>();
Step 4: Polulate the list at the time of Activity or fragment loaded:
public class GetVideoAsynctask extends AsyncTask<String, String,Object[]> {
ProgressDialog progressDialog ;
String response = "";
int offset, limit;
public GetVideoAsynctask(int offset1, int limit1) {
offset = offset1;
limit = limit1;
}
#Override
public void onPreExecute() {
progressDialog = ProgressDialog.show(getActivity(),"Loading...", "Please Wait");
}
#Override
public Object[] doInBackground(String... params) {
return AppParsing.getMediaDetails(getActivity(), AppPreferenceUtils.getChildUploadDeviceId(getActivity()),
AppPreferenceUtils.getChildRaId(getActivity()),"2", offset, limit,"3");
//// type=1 for image,2 for video,3 for audio
}
#SuppressWarnings("unchecked")
#Override
public void onPostExecute(Object[] result) {
progressDialog.cancel();
try
{
boolean status = (Boolean) result[0];
response = (String) result[1];
if(status)
{
videoDetailBeans = (ArrayList<MediaDetailBean>) result[2] ;
for (int i = 0; i < videoDetailBeans.size(); i++) {
videoDetailBeans_total.add(videoDetailBeans.get(i));
}
isCheck_video = new boolean[videoDetailBeans_total.size()];
for(int i=0;i<videoDetailBeans_total.size();i++)
{
if(!GRID_DATA.contains(videoDetailBeans_total.get(i).getAlbum()))
{
GRID_DATA.add(videoDetailBeans_total.get(i).getAlbum());
}
}
video_folder_gridView.setAdapter(new AlbumGridAdapter(getActivity(), videoDetailBeans_total));
//Toast.makeText(getActivity(), response, Toast.LENGTH_SHORT).show();
}
else
{
response = (String) result[1];
AppUtils.showDialog(getActivity(), response);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Step 5: Set the listview adapter like:
new GetVideoAsynctask(offset1, limit1).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Step 6: Most important thinning is i am taking load more list view here:
com.costum.android.widget.LoadMoreListView) video_folder_gridView = (com.costum.android.widget.LoadMoreListView) rootView.findViewById(R.id.video_folder_gridView);
Step 7: In my xml i am declaring like this:
<com.costum.android.widget.LoadMoreListView
android:id="#+id/video_folder_gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
Feel free if you have any query regarding this concept.
This is my implementation of Filter which filters while you type a single letter.This is the Activity implementation...
public class MessagesActivity extends Activity{
private ListView msgListView;
private EditText mSearchContent;
private MessagesAdapter msgAdapter;
public static ArrayList<MessagesBean> allMsgsList = new ArrayList<MessagesBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
init();
msgAdapter = new MessagesAdapter(getApplicationContext(), allMsgsList, MessagesActivity.this);
msgListView.setAdapter(msgAdapter);
}
private void init() {
// TODO Auto-generated method stub
msgListView = (ListView) findViewById(R.id.messages_list);
msgListView.setOnScrollListener(this);
mSearchContent.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void afterTextChanged(Editable s) {
msgAdapter.getFilter().filter(s.toString());
}
});
}
This is the Adapter implementation
public class MessagesAdapter extends BaseAdapter implements Filterable {
private Context mcontext;
private ArrayList<MessagesBean> all_details, dup_all_details;
private LayoutInflater inflater;
private DisplayImageOptions options;
private CustomClickLisntener clickLisntener;
private MessagesBean mMessagesBean;
private ViewHolder selectedHolder;
private ListViewFilter listviewFilter;
// int pos = 0;
public MessagesAdapter(Context context, ArrayList<MessagesBean> all_list, CustomClickLisntener lisntener) {
mcontext = context;
all_details = all_list;
clickLisntener = lisntener;
inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
dup_all_details = all_list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return all_details.size();
}
#Override
public MessagesBean getItem(int position) {
// TODO Auto-generated method stub
return all_details.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
static class ViewHolder {
TextView user_name, msg_sub, msg_content, msg_time;
ImageView user_image;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewholder = null;
if (convertView == null) {
viewholder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_item_inbox_msg, null);
viewholder.user_name = (TextView) convertView.findViewById(R.id.user_name);
viewholder.msg_time = (TextView) convertView.findViewById(R.id.msg_time);
viewholder.msg_sub = (TextView) convertView.findViewById(R.id.msg_subject);
viewholder.user_image = (ImageView) convertView.findViewById(R.id.user_image);
viewholder.msg_content = (TextView) convertView.findViewById(R.id.msg_content);
// viewholder.down_arrow.setTag(position);
convertView.setTag(viewholder);
} else {
viewholder = (ViewHolder) convertView.getTag();
}
mMessagesBean = all_details.get(position);
viewholder.user_name.setText(mMessagesBean.getFirstname().trim() + " " + mMessagesBean.getLastname());
viewholder.msg_time.setText(DateDifferent.getDateDifferance(mMessagesBean.getSentDate()));
viewholder.msg_sub.setText(mMessagesBean.getSubject());
viewholder.msg_content.setText(mMessagesBean.getMessage());
ImageLoader.getInstance().displayImage(mMessagesBean.getUserimage(), viewholder.user_image, options);
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
if (listviewFilter == null) {
listviewFilter = new ListViewFilter();
}
return listviewFilter;
}
public class ListViewFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
constraint = constraint.toString();
ArrayList<MessagesBean> allitems = new ArrayList<MessagesBean>();
FilterResults filterresults = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
for (int i = 0; i < dup_all_details.size(); i++) {
if (dup_all_details.get(i).getFirstname().contains(constraint)
|| dup_all_details.get(i).getLastname().contains(constraint)) {
allitems.add(dup_all_details.get(i));
}
}
filterresults.count = allitems.size();
filterresults.values = allitems;
} else {
System.out.println(" iam here..." + all_details.size());
synchronized (this) {
filterresults.count = allitems.size();
filterresults.values = allitems;
}
}
return filterresults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// TODO Auto-generated method stub
all_details = (ArrayList<MessagesBean>) results.values;
MessagesActivity.allMsgsList = all_details;
MessagesAdapter.this.notifyDataSetChanged();
}
}
}
You can do it like:
public void filter(String charText) {
drinks.clear();
if (charText.length() == 0) {
drinks.addAll(contact_list);
} else {
for (ContactLists wp : contact_list) {
if (wp.getContact_name().contains(charText)) {
drinks.add(wp);
}
}
}
contact_list.clear();
contact_list.addAll(drinks);
adapter.notifyDataSetChanged(contact_list);
}
and in your adapter:
public void notifyDataSetChanged(List<ContactLists> items){
this.categoryArrayList = items;
super.notifyDataSetChanged();
}

Issue with adding addTextChangedListener in adapter

I'm trying to implement a search function in my application. I have used an adapter to because I want to display 2 textviews in listview and listview should be clickable (I don;t think it's possible to do without an adapter).
My problem is I can't use addTextChangedListener in the adapter class. it gives exception (It worked in my activity class).
search activity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_results_activity);
new SearchMenuAsyncTask(getApplicationContext(), this).execute();
listtv = (LinearLayout) findViewById(R.id.product_lv);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
final List<String> descriptions = new ArrayList<String>();
final List<String> menudescriptions = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("5")
&& (object.getString("SubCategoryID")).equals("6")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsBev ", object.getString("Description"));
descriptions.add(object.getString("Description"));
Log.i("MenuDescription ",
object.getString("MenuDescription"));
menudescriptions
.add(object.getString("MenuDescription"));
}
adapter = new CustomListSearch(
getApplicationContext(), descriptions,
menudescriptions);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomListSearch.java
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
private final List<String> descriptions;
private List<String>filteredData = null;
private final List<String> menudescriptions;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
ArrayAdapter<String> adapter;
public CustomListSearch(Context c, List<String> data,
List<String> menudescriptions) {
this.context = c;
this.filteredData = data ;
this.descriptions = data;
this.menudescriptions = menudescriptions;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView
.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView
.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(descriptions.get(position));
holder.tvMenudescriptions.setText(menudescriptions.get(position));
LinearLayout itemlist = (LinearLayout) convertView
.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",
Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = descriptions;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
I was following below answer and worked this out
Custom Listview Adapter with filter Android

Loading the filtered items to search output

I have implement search for my application. For that I have used an adapter as well. I have loaded 30 items to the search screen. When I pressed letter z to search, then letter z belongs to 4 items out of 30 items in the list.
According to the below shown code it identifies the number 4 and shows the first 4 items out of the 30 items. When I debug inside getFilter(), it shows the filtered items correctly(I have provided a screen shot).
My problem is how can I load the filtered items. Bit confused here.
search.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_results_activity);
new SearchMenuAsyncTask(getApplicationContext(), this).execute();
listtv = (LinearLayout) findViewById(R.id.product_lv);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
lv.setTextFilterEnabled(true);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
adapter.getFilter().filter(s.toString());
TextView headerTV = (TextView) findViewById(R.id.search_header);
headerTV.setText("SEARCH RESULTS");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
final List<String> menudescriptions = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsTop ", object.getString("Description"));
descriptions.add(object.getString("Description"));
Log.i("MenuDescription ",
object.getString("MenuDescription"));
menudescriptions
.add(object.getString("MenuDescription"));
}
adapter = new CustomListSearch(
getApplicationContext(), descriptions,
menudescriptions);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomListSearch.java
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
List<String> descriptions;
private List<String>filteredDescriptions;
private final List<String> menudescriptions;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
ArrayAdapter<String> adapter;
public CustomListSearch(Context c, List<String> data,
List<String> menudescriptions) {
this.context = c;
this.filteredDescriptions = data ;
this.descriptions = data;
this.menudescriptions = menudescriptions;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filteredDescriptions.size();
}
#Override
public Object getItem(int position) {
return filteredDescriptions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView
.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView
.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(descriptions.get(position));
holder.tvMenudescriptions.setText(menudescriptions.get(position));
LinearLayout itemlist = (LinearLayout) convertView
.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",
Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = descriptions;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredDescriptions = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
Screen shot
To filter adapter that contains list of custom object
Create a Object:
public class TvObject {
String name;
String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
After:
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
private List<TvObject> mListTvObject = new ArrayList<>();
private List<TvObject> mListTvObjectFiltered = new ArrayList<>();
public CustomListSearch(Context c, List<TvObject> mListTvObject) {
this.context = c;
mInflater = LayoutInflater.from(context);
this.mListTvObject = mListTvObject;
this.mListTvObjectFiltered = mListTvObject;
}
#Override
public int getCount() {
return mListTvObjectFiltered.size();
}
#Override
public Object getItem(int position) {
return mListTvObjectFiltered.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(mListTvObjectFiltered.get(position).getName());
holder.tvMenudescriptions.setText(mListTvObjectFiltered.get(position).getDescription());
LinearLayout itemlist = (LinearLayout) convertView.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = mListTvObject.size();
final ArrayList<TvObject> mListResult = new ArrayList<>();
String name;
for (int i = 0; i < count; i++) {
TvObject mTvObject = mListTvObject.get(i);
name = mTvObject.getName();
if (name.toLowerCase().contains(filterString)) {
mListResult.add(mTvObject);
}
}
results.values = mListResult;
results.count = mListResult.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
mListTvObjectFiltered = (ArrayList<TvObject>) results.values;
notifyDataSetChanged();
}
}
}
Edited:
In your Activity do something like this!
try {
final List<TvObject > mListObjects = new ArrayList<>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsTop ", object.getString("Description"));
Log.i("MenuDescription ", object.getString("MenuDescription"));
TvObject mTvObject = new TvObject();
mTvObject.setName(object.getString("Description"));
mTvObject.setDescription(object.getString("MenuDescription"));
mListObjects.add(mTvObject);
}
adapter = new CustomListSearch( getApplicationContext(), mListObjects);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}

how can i get the current position of listView after it getFilter()?

My question asked before : Link .If you do not understand me.
I have a listView with baseAdapter class on my app and my problem is:
User typing on the editText some letter in it and after the listView return him the all "Names" with this letter(addTextChangedListener) . now,
Evrything work fine but when the adapter set the "new list" with the result ,I Can't get the current Data from the current position from the list. Explain the theory :
my list is :
posistion 0. Name: A Phone: 111111
posistion 1. Name: B Phone: 222222
posistion 2. Name: C Phone: 333333
and when i type the letter "C" my list show this result:
position 0 : Name C: Phone: 111111 (phone is"111111" because that target to position "0")
but in "0" position i have the Phone value of A .
Here my code:
public class MainActivity extends Activity implements OnClickListener, OnItemClickListener {
ListView lv;
ArrayList<Person> contactList;
CustomContact adapterContact;
//Temp
ArrayList<String> groupList = new ArrayList<>();
ArrayList<String> groupListName = new ArrayList<>();
ArrayList<Person> tempList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button) findViewById(R.id.bSend);
send.setOnClickListener(this);
txTempName = (TextView) findViewById(R.id.textTempName);
edNumber = (EditText)findViewById(R.id.edPhoneOrName);
edMass = (EditText)findViewById(R.id.edMass);
timepicker = (TimePicker)findViewById(R.id.timePickerMain);
timepicker.setIs24HourView(true);
datePicker = (DatePicker) findViewById(R.id.datePickerMain);
lv = (ListView) findViewById(R.id.listContact);
lv.setOnItemClickListener(this);
edNumber.addTextChangedListener(new TextWatcher() {
#SuppressWarnings("unchecked")
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().equalsIgnoreCase("")) {
refreshContact();
} else {
MainActivity.this.adapterContact.getFilter().filter(s);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
// // TODO Auto-generated method stub
}
});
}
public void refreshContact(){
DbHandContact hand = new DbHandContact(this);
hand.open();
contactList = hand.getAll();
hand.close();
Collections.sort(contactList,contactSort);
adapterContact = new CustomContact(this, contactList);
lv.setAdapter(adapterContact);
tempList = (ArrayList<Person>) contactList.clone();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(true){
String currentCellPhone = tempList.get(position).getCellPhone();
String name = tempList.get(position).getName();
groupList.add(currentCellPhone);
groupListName.add(name);
Toast.makeText(this, currentCellPhone+" "+name, 2000).show();
for (int i = 0; i < groupList.size(); i++) {
txTempName.setText(groupList.get(i));
}
}
}
My Adapter class:
public class CustomContact extends BaseAdapter implements Filterable {
Activity context;
ArrayList<Person> list;
protected ArrayList<String> temporarylist;
public CustomContact(Activity context, ArrayList<Person> list) {
super();
this.context = context;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
LayoutInflater inflater = context.getLayoutInflater();
row = inflater.inflate(R.layout.row_contact, parent,false);
ImageView imgPerson,ImgDial;
TextView txName,txLastName,txCellnum,HomeNum;
txName = (TextView) row.findViewById(R.id.row_name);
txLastName = (TextView) row.findViewById(R.id.row_lastName);
txCellnum = (TextView) row.findViewById(R.id.row_cellNum);
imgPerson = (ImageView) row.findViewById(R.id.row_picture);
txName.setText(list.get(position).getName());
txLastName.setText(list.get(position).getLastName());
txCellnum.setText(list.get(position).getCellPhone());
return row;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<Person>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<Person> FilteredList = new ArrayList<Person>();
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = list;
results.count = list.size();
} else {
for (int i = 0; i < list.size(); i++) {
String data = list.get(i).getName();
if (data.toLowerCase().contains(constraint.toString().toLowerCase())) {
FilteredList.add(list.get(i));
}
}
results.values = FilteredList;
results.count = FilteredList.size();
}
return results;
}
};
return filter;
}
}
Try this code Filter part code only change:
#Override public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
list = (ArrayList<Person>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<Person> FilteredList = new ArrayList<Person>();
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = list;
results.count = list.size();
} else {
constraint = constraint.toString();
for (int i = 0; i < list.size(); i++) {
String data = list.get(i).getName();
if (data.toLowerCase().contains(constraint.toString())) {
FilteredList.add(list.get(i));
}
results.values = FilteredList;
results.count = FilteredList.size();
}
return results;
}
};
return filter;
}
and editext code here:
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// Call back the Adapter with current character to Filter
mAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
you can solve this issue by one of two cases that you can use application class and when it updated in adapter update it in the application class and then you can access from the activity/fragment and whenever you want
and the second option to use sharedpreferences to save it and the same for retrieving it at any place also

Categories

Resources