This question already has answers here:
EditText loses content on scroll in ListView
(11 answers)
Closed 5 years ago.
I try make listview with edittext for in. But my apdater not work as expected. When i scroll down then scroll up, so values in first editext is lost.
My dapter:
public class ArrayAdapterListProduct extends BaseAdapter implements Filterable {
private ArrayList<ProductItem> listProductItems = new ArrayList<>();
private ArrayList<ProductItem> mOriginalValues = new ArrayList<>();
private Context context = null;
private Activity a = null;
static class ViewHolder {
TextView text;
TextView timestamp;
ImageView icon;
EditText caption;
ProgressBar progress;
int position;
}
public ArrayAdapterListProduct(Activity a, Context context, ArrayList<ProductItem> productItems) {
this.listProductItems = productItems;
this.mOriginalValues = productItems;
this.context = context;
this.a = a;
}
public void swapItem(ArrayList<ProductItem> productItems) {
this.listProductItems = productItems;
notifyDataSetChanged();
}
#Override
public int getCount() {
return listProductItems.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(this.context);
view = inflater.inflate(R.layout.layout_lv_item, null);
holder.caption = (EditText) view.findViewById(R.id.earnpoit_listview_item_number);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.caption = (EditText) view.findViewById(R.id.earnpoit_listview_item_number);
view.setTag(holder);
if (position % 2 != 0) {
view.setBackgroundColor(parent.getResources().getColor(R.color.earnpoint_color_bg_item_lv));
} else {
view.setBackgroundColor(parent.getResources().getColor(R.color.WHITE));
}
final ProductItem productItem = listProductItems.get(position);
TextView txt_name = (TextView) view.findViewById(R.id.earnpoit_listview_item_productname);
TextView txt_exist = (TextView) view.findViewById(R.id.earnpoit_listview_item_exist);
txt_name.setText(productItem.getName());
txt_exist.setText(productItem.getQuantity() + "");
holder.caption.setText(productItem.getNumber_choose() + "");
holder.caption.setId(position);
holder.caption.addTextChangedListener(new MyTextWatcher(holder.caption));
holder.caption.setFilters(new InputFilter[]{new InputFilterMinMax(0, Integer.parseInt(txt_exist.getText().toString()))});
return view;
}
private class MyTextWatcher implements TextWatcher {
private EditText editText;
private MyTextWatcher(EditText editText) {
this.editText = editText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
final int position = this.editText.getId();
final EditText Caption = (EditText) this.editText;
listProductItems.get(position).setNumber_choose(Integer.parseInt(Caption.getText().toString()));
TextView txt_point_to_product = (TextView) a.findViewById(R.id.sellout_txt_point_in_order);
Double total_point = 0.0;
for (int i = 0; i < listProductItems.size(); i++) {
ProductItem productItem1 = listProductItems.get(i);
if (productItem1.getNumber_choose() > 0) {
total_point = total_point + productItem1.getNumber_choose()*productItem1.getPoint();
}
}
txt_point_to_product.setText(total_point + "");
}
#Override
public void afterTextChanged(Editable s) {
}
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<ProductItem> filterArray = new ArrayList<ProductItem>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<>(listProductItems);
}
if (constraint == null || constraint.length() == 0) {
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).getName();
if (data.toLowerCase().startsWith(constraint.toString())) {
filterArray.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = filterArray.size();
results.values = filterArray;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
listProductItems = (ArrayList<ProductItem>) results.values;
notifyDataSetChanged();
}
};
return filter;
}
}
Please help me. Thanks you!
Please refer below
holder.edtitext.setTag(position); // add this line
holder.edtitext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int pos = (Integer) holder.edtitext.getTag();
ProductItem productItem1 = listProductItems.get(pos);
// do your work
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Related
I created a listview which using customise adapter and I want to filter the listview by typing in edittext. However, I found it difficult because I get all the data from Firebase. How could I filter the data by name? What code do I need to add?
It is my main activity
private void readFirebaseData() {
FirebaseDatabase.getInstance().getReference("account").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
uid = (String) snapshot.child("uid").getValue();
contactNo = (String) snapshot.child("contactNo").getValue();
email = (String) snapshot.child("email").getValue();
name = (String) snapshot.child("name").getValue();
Shop shops = new Shop(uid, contactNo, email, name);
shopListAdapter adapter = new shopListAdapter(getActivity(), shop);
adapter.add(shops);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
private void filter() {
searcher.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
It is my adapter class
public class shopListAdapter extends ArrayAdapter<Shop> {
private ArrayList<Shop> shops;
Filter filter;
public shopListAdapter(Context context, ArrayList<Shop> shops) {
super(context, 0, shops);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Shop shops = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.txtName);
TextView address = (TextView) convertView.findViewById(R.id.txtAdd);
name.setText(shops.getShopName());
address.setText(shops.getAddress());
return convertView;
}
Plz try to add this .Ur running code are somethings wrong
public class MyLeadsAdapter extends ArrayAdapter<MyleadsListModel> {
private Vector<MyleadsListModel> originalList;
private Vector<MyleadsListModel> numberList;
private CountryFilter filter;
private Context context;
public MyLeadsAdapter(Context context, int textViewResourceId, Vector<MyleadsListModel> numberList) {
super(context, textViewResourceId, numberList);
this.context = context;
this.numberList = new Vector<MyleadsListModel>();
this.numberList.addAll(numberList);
this.originalList = new Vector<MyleadsListModel>();
this.originalList.addAll(numberList);
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new CountryFilter();
}
return filter;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
final MyViewHolder mViewHolder;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_my_leads,
null);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
return convertView;
}
class MyViewHolder {
}
private class CountryFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
Vector<MyleadsListModel> filteredItems = new Vector<MyleadsListModel>();
for (int i = 0, l = originalList.size(); i < l; i++) {
MyleadsListModel contactList = originalList.get(i);
if (contactList.getName().toString().toLowerCase()
.contains(constraint))
filteredItems.add(contactList);
}
result.count = filteredItems.size();
result.values = filteredItems;
} else {
synchronized (this) {
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
numberList = (Vector<MyleadsListModel>) results.values;
notifyDataSetChanged();
clear();
for (int i = 0, l = numberList.size(); i < l; i++)
add(numberList.get(i));
notifyDataSetInvalidated();
}
}
}
Add this code for Edittext :
searcher.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
I have a listview with edittext in each row using a textwatcher to show a toast of content input.
The textwatcher works fine for all the rows except the first row. The toast after input of text fires up consistently after you input text instead of showing only once.
The other rows respond well to the desired behaviour by displaying the toast once every time you change input. The default values for the inputs is 0.
Here is my code inside getView() of my adapter:
//tvItems is my edittext variable reference
TextWatcher tt = new TextWatcher() {
public void afterTextChanged(Editable s) {
//tvItems.setSelection(s.length());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
tvItems.removeTextChangedListener(tt);
if (tvItems.getText().toString().trim().length() == 1) {
//to check if input is greater than 0 so we can proceed
if (Integer.valueOf(tvItems.getText().toString().trim()) > 0) {
//displays toast
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
tvItems.removeTextChangedListener(tt);
}
}
tvItems.addTextChangedListener(tt);
}
};
tvItems.addTextChangedListener(tt);
Any suggestions will be welcomed.
As requested, my full adapter code:
public class ProductListAdapter extends BaseAdapter implements Filterable {
List<ProductModel> mStringFilterList;
ValueFilter valueFilter;
int item_number = 0;
TextWatcher tt = null;
private Activity activity;
private LayoutInflater inflater;
private List<ProductModel> modelItems;
private OnAddRemoveListener myaddInterface;
TextView tvTitle;
Button minusIcon, addIcon;
public ProductListAdapter(Activity activity, List<ProductModel> modelItems, OnAddRemoveListener myaddInterface) {
this.activity = activity;
this.modelItems = modelItems;
mStringFilterList = modelItems;
this.myaddInterface = myaddInterface;
}
#Override
public int getCount() {
return modelItems.size();
}
#Override
public Object getItem(int location) {
return modelItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}/*
#Override
public boolean isEnabled(int position) {
return false;
}*/
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.product_item_row, null);
final ProductModel m = modelItems.get(position);
tvTitle = (TextView) convertView.findViewById(R.id.tv2);
TextView tprice = (TextView) convertView.findViewById(R.id.tv3);
boolean ignoreNextTextChange = true;
final EditText tvItems = (EditText) convertView.findViewById(R.id.num);
tvItems.setText("0");
minusIcon = (Button) convertView.findViewById(R.id.minus);
addIcon = (Button) convertView.findViewById(R.id.add);
//add items
addIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("add button", "clicked");
int new_item_number = 1 + Integer.parseInt(tvItems.getText().toString());
tvItems.setText("" + new_item_number);
(myaddInterface).onItemadded(String.valueOf(m.getPrice()), new_item_number, position);
}
});
minusIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("minus button", "clicked");
int new_item_number = Integer.parseInt(tvItems.getText().toString());
if (new_item_number > 0) {
(myaddInterface).onItemremoved(String.valueOf(m.getPrice()), position);
tvItems.setText("" + (new_item_number - 1));
} else if (tvItems.getText().toString().equals("0")) {
tvItems.setText("0");
}
}
});
tvTitle.setText(m.getname());
tprice.setText("(" + m.getPrice() + ")");
public void afterTextChanged(Editable s) {
if (tvItems.getText().toString().trim().length() == 1) {
//to check if input is greater than 0 so we can proceed
if (Integer.valueOf(tvItems.getText().toString().trim()) > 0) {
//displays toast
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
tvItems.addTextChangedListener(tt);
return convertView;
}
//code for search filter, not associated with the question
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<ProductModel> filterList = new ArrayList<>();
for (int i = 0; i < mStringFilterList.size(); i++)
if ((mStringFilterList.get(i).getname().toUpperCase())
.contains(constraint.toString().toUpperCase()) || (mStringFilterList.get(i).getproductDesc().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ProductModel m = new ProductModel(mStringFilterList.get(i)
.getProduct_id(), mStringFilterList.get(i)
.getname(), mStringFilterList.get(i)
.getPrice(), mStringFilterList.get(i)
.getimage_url(), mStringFilterList.get(i)
.getproductDesc());
filterList.add(m);
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
//show no results
}
/* }else if((mStringFilterList.get(i).getproductDesc().toUpperCase())
.contains(constraint.toString().toUpperCase())){}*/
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
modelItems = (List<ProductModel>) results.values;
notifyDataSetChanged();
}
}
}
set the listener object to edittext,(i.e) tt ,like this
editText.addTextChangedListener(tt);
Can you try this instead:
TextWatcher tt = new TextWatcher() {
public void afterTextChanged(Editable s) {
if (tvItems.getText().toString().trim().length() == 1) {
//to check if input is greater than 0 so we can proceed
if (Integer.valueOf(tvItems.getText().toString().trim()) > 0) {
//displays toast
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
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();
}
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.
I'm trying to filter a custom ListView - from a ListActivity. The problem is, while the filter is actually working, the ListView is not displaying correctly.
If for example I have 3 items each starting with a, b, c, da, db respectively, typing in e will show that the ListView is empty. However, when I type in b, it will show a, and when I type in c, it will show a. When I type in d, it will show a, b. I'm not entirely certain what I did wrong or what I'm missing to have that issue. It appears that the position isn't being passed to the filter, but how would I go about doing this?
Below is the my ArrayAdapter:
private class SiteAdapter extends ArrayAdapter<Site> {
private ArrayList<Site> sites;
public SiteAdapter(Context context, int textViewResourceId, ArrayList<Site> sites) {
super(context, textViewResourceId, sites);
this.sites = sites;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Site s = this.sites.get(position);
if (s != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView rt = (TextView) v.findViewById(R.id.statustext);
if (tt != null) {
tt.setText("sup2");
}
if (bt != null) {
bt.setText("sup");
}
if (rt != null) {
rt.setText("sup");
}
}
v.setOnClickListener(new OnItemClickListener(position));
return v;
}
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
//Log.v("MainActivity", sites.get(mPosition).getURL());
Intent intent = new Intent(getBaseContext(), Wee.class);
startActivityForResult(intent,1);
}
}
}
private TextWatcher filterTextWatcher = 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) {
site_adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
My Object Class has:
#Override
public String toString() {
return new StringBuilder()
.append(this.SEARCHABLE).toString();
}
I got it down to filtering correctly, but now the filter isn't returning the Listview to its original state when deleting or emptying the text box. I got the example from Custom Filtering ArrayAdapter in ListView:
private class SiteFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0) {
ArrayList<Site> list = new ArrayList<Site>(sites);
results.values = list;
results.count = list.size();
} else {
final ArrayList<Site> list = new ArrayList<Site>(sites);
final ArrayList<Site> nlist = new ArrayList<Site>();
int count = list.size();
for (int i = 0; i < count; i++) {
final Site pkmn = list.get(i);
final String value = pkmn.getFILTERABLETEXT().toLowerCase();
if (value.startsWith(prefix)) {
nlist.add(pkmn);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filtered_sites = (ArrayList<Site>) results.values;
clear();
int count = filtered_sites.size();
for (int i = 0; i < count; i++) {
Site pkmn = (Site) filtered_sites.get(i);
add(pkmn);
}
}
}
Chandra's advice:
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filtered_sites = (ArrayList<Site>) results.values;
site_adapter.notifyDataSetChanged();
clear();
int count = filtered_sites.size();
for (int i = 0; i < count; i++) {
Site pkmn = (Site) filtered_sites.get(i);
add(pkmn);
Log.d("OMGOMGOMG",pkmn.getURL());
}
site_adapter.notifyDataSetInvalidated();
}
I think its not notifying the change in data. Add notifyDataSetChanged in method onTextChanged
public void onTextChanged(CharSequence s, int start, int before, int count) {
site_adapter.getFilter().filter(s);
site_adapter.notifyDataSetChanged();
}