Textwatcher not working - android

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) {
}
};

Related

Get data from multiple spinners generated dynamically in linearLayout

I am trying to add a dynamic view inside my LinearLayout and trying to implement something like to catch every spinner value corresponding to time. Can anyone over here can guide me that how it can be done. I am trying it but it's not working as there can be infinite rows with spinners based on the click on the "ADD FILED" button. I need to collect value from each spinner and need to create an array then.
Here is my code :
public class MainActivity extends Activity {
private LinearLayout parentLinearLayout;
private EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parentLinearLayout=(LinearLayout) findViewById(R.id.parent_linear_layout);
}
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.container_item, null);
final EditText text1 = (EditText) rowView.findViewById(R.id.number_edit_text);
final EditText text2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
final EditText text3 = (EditText) rowView.findViewById(R.id.number_edit_text3);
text1.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() > 0) {
text3.setText(text1.getText().toString());
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text2.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() > 0) {
int val = Integer.parseInt(text1.getText().toString());
int val2 = Integer.parseInt(text2.getText().toString());
if(val2>val)
{
}else{
int finalval=val-val2;
text3.setText(""+finalval);
}
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text3.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() > 0) {
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
public void onGetField(View v){
int count = parentLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
final View row = parentLinearLayout.getChildAt(i);
EditText textOut = (EditText) row.findViewById(R.id.number_edit_text);
String data = textOut.getText().toString();
Toast.makeText(this,""+data,Toast.LENGTH_LONG).show();
}
}
}
Dynamic view XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:id="#+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<EditText
android:id="#+id/number_edit_text2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<EditText
android:id="#+id/number_edit_text3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<Spinner
android:id="#+id/type_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".3"
android:entries="#array/types"
android:gravity="right" />
<Button
android:id="#+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight=".1"
android:background="#android:drawable/ic_delete"
android:onClick="onDelete"/>
</LinearLayout>
Main XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/parent_linear_layout"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<Button
android:id="#+id/add_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onAddField"
android:textColor="#FFF"
android:text="Add Field"
android:paddingLeft="5dp"/>
<Button
android:id="#+id/get_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onGetField"
android:textColor="#FFF"
android:text="Get Field"
android:paddingLeft="5dp"/>
</LinearLayout>
Please let me know your valuable suggestions on this. I have been stuck since the last day.
Here is the attached image and in the image you can see that the 3rd edit text is empty which I need to fill by using text watcher on 1st two edit-text like 2(first edit-text)-1(second edit-text) = 1 (on thrid edit-text).
Regards
Below is the second approach using Recyclerview:
MainActivity:
public class MainActivity extends AppCompatActivity {
int position=0;
List<Container_Add_model> main_modelList = new ArrayList<>();
RecyclerView recyclerView_container;
TextView Tv_add_container;
Container_Add_Adapter rvAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView_container = findViewById(R.id.recyclerView_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView_container.setLayoutManager(layoutManager);
Tv_add_container = findViewById(R.id.Tv_add_container);
rvAdapter = new Container_Add_Adapter(MainActivity.this, main_modelList,this, new Container_Add_Adapter.Onclick() {
#Override
public void onEvent(Container_Add_model model, int pos) {
}
});
recyclerView_container.setAdapter(rvAdapter);
Tv_add_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rvAdapter.addClick();
}
});
}
Adapter Class :
public class Container_Add_Adapter extends RecyclerView.Adapter<Container_Add_Adapter.RvViewHolder> {
Activity context;
List<Container_Add_model> models;
Onclick onclick;
View view;
EditTextAdded editTextAdded;
private int container_number_pending, container_number_taken, container_number_given;
public Container_Add_Adapter(Activity context, List<Container_Add_model> models,EditTextAdded editTextAdded, Onclick onclick) {
this.context = context;
this.models = models;
this.editTextAdded = editTextAdded;
this.onclick = onclick;
}
#Override
public Container_Add_Adapter.RvViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.from(parent.getContext()).inflate(R.layout.container_item, parent, false);
RvViewHolder rvViewHolder = new RvViewHolder(view);
return rvViewHolder;
}
#Override
public void onBindViewHolder(final Container_Add_Adapter.RvViewHolder holder, final int position) {
final Container_Add_model model = models.get(position);
holder.Edttxt_given_container.setText(models.get(position).container_given+"");
holder.Edttxt_given_container.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() > 0) {
// models.get(position).container_given = Integer.valueOf(s.toString());
}
}
});
holder.Edttxt_taken_container.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() != 0) {
if (!holder.Edttxt_given_container.getText().toString().isEmpty()) {
container_number_given = Integer.parseInt(holder.Edttxt_given_container.getText().toString());
int number = container_number_given + container_number_pending;
int input_num = Integer.parseInt(s.toString());
if (number >= input_num) {
container_number_taken = Integer.parseInt(holder.Edttxt_taken_container.getText().toString());
int final_num = number - container_number_taken;
holder.Edttxt_Pending_container.setText("" + final_num);
} else {
holder.Edttxt_taken_container.setText("");
}
} else {
holder.Edttxt_taken_container.setText("");
}
} else {
if (!holder.Edttxt_given_container.getText().toString().isEmpty()) {
container_number_given = Integer.parseInt(holder.Edttxt_given_container.getText().toString());
if (container_number_given > 0) {
int finalnum = container_number_given + container_number_pending;
holder.Edttxt_Pending_container.setText("" + finalnum);
} else {
holder.Edttxt_Pending_container.setText("" + container_number_pending);
}
} else {
holder.Edttxt_Pending_container.setText("" + container_number_pending);
}
}
}
});
holder.Iv_delete_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
models.remove(position);
notifyItemChanged(position);
notifyItemRangeChanged (position, models.size());
}
});
}
public void addClick(){
Container_Add_model container_main_model = new Container_Add_model();
container_main_model.setContainer_given(0);
container_main_model.setContainer_pending(0);
container_main_model.setContainer_taken(0);
container_main_model.setContainer_id(models.size());
container_main_model.setContainer_name("");
models.add(container_main_model);
//notifyDataSetChanged(models);
notifyItemInserted(models.size() + 1);
}
#Override
public int getItemCount() {
return models.size();
}
public interface Onclick {
void onEvent(Container_Add_model model, int pos);
}
public class RvViewHolder extends RecyclerView.ViewHolder {
TextView Tv_container_type;
EditText Edttxt_given_container, Edttxt_taken_container, Edttxt_Pending_container;
LinearLayout llItem;
ImageView Iv_delete_container;
public RvViewHolder(View itemView) {
super(itemView);
Tv_container_type = itemView.findViewById(R.id.Tv_container_type);
Iv_delete_container = itemView.findViewById(R.id.Iv_delete_container);
Edttxt_given_container = itemView.findViewById(R.id.Edttxt_given_container);
Edttxt_Pending_container = itemView.findViewById(R.id.Edttxt_Pending_container);
Edttxt_taken_container = itemView.findViewById(R.id.Edttxt_taken_container);
}
}
}
Here is what you were missing :
public class MainActivity extends Activity {
private LinearLayout parentLinearLayout;
private ArrayList<> mList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parentLinearLayout=(LinearLayout) findViewById(R.id.parent_linear_layout);
}
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.container_item, null);
final EditText text1 = (EditText) rowView.findViewById(R.id.number_edit_text);
final EditText text2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
final EditText text3 = (EditText) rowView.findViewById(R.id.number_edit_text3);
final Spinner mSpinner = (Spinner) rowView.findViewById(R.id.type_spinner);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedDiv = parent.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this, ""+selectedDiv, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// can leave this empty
}
});
text1.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() > 0) {
text3.setText(text1.getText().toString());
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text2.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() > 0) {
int val = Integer.parseInt(text1.getText().toString());
int val2 = Integer.parseInt(text2.getText().toString());
if(val2>val)
{
}else{
int finalval=val-val2;
text3.setText(""+finalval);
}
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text3.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#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 (s.length() > 0) {
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
public void onGetField(View v){
mList = new ArrayList<>();
int count = parentLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
final View row = parentLinearLayout.getChildAt(i);
EditText textOut = (EditText) row.findViewById(R.id.number_edit_text);
EditText textOut2 = (EditText) row.findViewById(R.id.number_edit_text2);
EditText textOut3 = (EditText) row.findViewById(R.id.number_edit_text3);
Spinner spinner = (Spinner)row.findViewById(R.id.type_spinner);
mList.add(new DataList( textOut.getText().toString(),
textOut2.getText().toString()
, textOut3.getText().toString(),spinner.getSelectedItem().toString()
));
}
}
}
Datalist Model :
public class DataList {
public String given;
public String taken;
public String pending;
public String spinnerItemSelected;
public DataList(String given, String taken, String pending, String spinnerItemSelected) {
this.given = given;
this.taken = taken;
this.pending = pending;
this.spinnerItemSelected = spinnerItemSelected;
}
}
Convert your String array to ArrayList and pass it to Adapter and use below code or change below code with your String[].
You need to implement Filterable to your Adapter class and Override getFilter()
public class ListFilterActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
List<String> mOriginalValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyAdapter adapter = new MyAdapter(this, getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
// Add Text Change Listener to EditText
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<String> getModel() {
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("iPhone");
list.add("Windows XP");
return list;
}
}
// Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<String> arrayList;
List<String> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<String> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(arrayList.get(position));
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
arrayList = (List<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}

Edittext in Listview when scroll so lost data [duplicate]

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) {
}
});

ListView filter data in edittext

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) {
}
});

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();
}

TextWatcher filter for an object with custom toString()

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();
}

Categories

Resources