position of checkbox get change - android

I am trying to apply filter on my custom adapter which extends BaseAdapter, in which I am facing some problems, after I filter input based on the text in EditText and check the CheckBox to select one value and if I erase the text in the EditText to search for some other thing the position of the checked checkbox changes.
MainActivty
public class MainActivity extends Activity implements OnItemClickListener {
EditText searchText;
ArrayList<String> phno0 = new ArrayList<String>();
List<String> arrayListNames;
// private ListView listview;
// private EditText edittext;
public List<ProfileBean> list;
public SearchableAdapter adapter;
ProfileBean bean;
String[] cellArray = null;
String contacts;
ListView lv;
String phoneNumber, name;
// StringBuilder b = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#00aef0"));
actionBar.setBackgroundDrawable(colorDrawable);
setContentView(R.layout.get);
// mStatusView = (TextView) findViewById(R.id.text1);
searchText = (AutoCompleteTextView) findViewById(R.id.autocomplete);
lv = (ListView) findViewById(R.id.listview);
list = new ArrayList<ProfileBean>();
getAllCallLogs(this.getContentResolver());
adapter = new SearchableAdapter(getApplicationContext(), list);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(this);
lv.setTextFilterEnabled(true);
contacts = SmsSend.contacts;
if (SmsSend.contacts != null) {
cellArray = contacts.split(";");
//contacts=null;
// Toast.makeText(getApplication(), contacts.toString(),
// Toast.LENGTH_LONG).show();
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list.size(); j++) {
if (cellArray[i].equals(list.get(j).getNumber())) {
adapter.setChecked(j, true);
// break;
}
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.contact_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
//StringBuilder checkedcontacts = new StringBuilder();
// System.out.println(".............." +
// adapter.mCheckStates.size());
for (int i = 0; i < list.size(); i++)
{
if (adapter.mCheckStates.get(i) == true) {
phno0.add(list.get(i).getNumber());
//checkedcontacts.append(list.get(i).toString());
// checkedcontacts.append("\n");
// Toast.makeText(getApplicationContext(),
// list.get(i).getNumber().toString(),
// Toast.LENGTH_LONG).show();
} else {
System.out.println("..Not Checked......"
+ list.get(i).getNumber().toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
break;
case R.id.addPage:
break;
case R.id.action_search:
searchText.setVisibility(View.VISIBLE);
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
}
#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.toString());
}
});
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
phno0.clear();
//StringBuilder checkedcontacts = new StringBuilder();
// System.out.println(".............." + adapter.mCheckStates.size());
for (int i = 0; i < list.size(); i++)
{
if (adapter.mCheckStates.get(i) == true) {
phno0.add(list.get(i).getNumber());
} else {
System.out.println("..Not Checked......"
+ list.get(i).getNumber().toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
// TODO Auto-generated method stub
adapter.toggle(position);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
list.add(new ProfileBean(name, phoneNumber));
}
phones.close();
}
}
SearchableAdapter
public class SearchableAdapter extends BaseAdapter implements Filterable, OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
private List<ProfileBean>originalData = null;
private List<ProfileBean>filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<ProfileBean> data) {
//mCheckStates = new SparseBooleanArray(filteredData.size());
mCheckStates = new SparseBooleanArray(data.size());
this.filteredData = data ;
this.originalData = data ;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.textView1);
holder.number = (TextView) convertView.findViewById(R.id.textView2);
holder.chk = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.chk.setTag(position);
convertView.setTag(R.layout.row,holder);
} else {
holder = (ViewHolder) convertView.getTag(R.layout.row);
}
holder.chk.setOnCheckedChangeListener(null);
holder.chk.setOnCheckedChangeListener(this);
ProfileBean bean = filteredData.get(position);
holder.name.setText(bean.getName());
holder.number.setText(bean.getNumber());
convertView.setTag(bean);
return convertView;
}
static class ViewHolder {
TextView name;
TextView number;
CheckBox chk;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<ProfileBean> list = originalData;
int count = list.size();
final ArrayList<ProfileBean> nlist = new ArrayList<ProfileBean>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
ProfileBean bean = list.get(i);
filterableString = bean.getName();
if (filterableString.toLowerCase().contains(filterString.toString().toLowerCase())) {
nlist.add(bean);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<ProfileBean>) results.values;
notifyDataSetChanged();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
ProfileBean Class
public class ProfileBean {
private String name;
private String number;
//private boolean checked = false ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public ProfileBean(String name, String number) {
super();
this.name = name;
this.number = number;
}
}

Change your Adapter like this..
public class SearchableAdapter extends BaseAdapter implements Filterable,
OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
private List<ProfileBean> originalData = null;
private List<ProfileBean> filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<ProfileBean> data) {
// mCheckStates = new SparseBooleanArray(filteredData.size());
mCheckStates = new SparseBooleanArray(data.size());
this.filteredData = data;
this.originalData = data;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.textView1);
holder.number = (TextView) convertView.findViewById(R.id.textView2);
holder.chk = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.chk.setTag(position);
convertView.setTag(R.layout.row, holder);
} else {
holder = (ViewHolder) convertView.getTag(R.layout.row);
}
ProfileBean bean = filteredData.get(position);
holder.name.setText(bean.getName());
holder.number.setText(bean.getNumber());
holder.chk.setOnCheckedChangeListener(null);
holder.chk.setChecked(bean.isChecked);
holder.chk.setOnCheckedChangeListener(this);
convertView.setTag(bean);
return convertView;
}
static class ViewHolder {
TextView name;
TextView number;
CheckBox chk;
}
public void toggle(int position) {
ProfileBean bean = filteredData.get(position);
bean.isChecked = !bean.isChecked;
}
public android.widget.Filter getFilter() {
return mFilter;
}
private class ItemFilter extends android.widget.Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<ProfileBean> list = originalData;
int count = list.size();
final ArrayList<ProfileBean> nlist = new ArrayList<ProfileBean>(
count);
String filterableString;
for (int i = 0; i < count; i++) {
ProfileBean bean = list.get(i);
filterableString = bean.getName();
if (filterableString.toLowerCase().contains(
filterString.toString().toLowerCase())) {
nlist.add(bean);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
filteredData = (ArrayList<ProfileBean>) results.values;
notifyDataSetChanged();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int position = (Integer) buttonView.getTag();
ProfileBean profileBean = filteredData.get(position);
profileBean.isChecked = isChecked;
// mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
and your bean class like..
public class ProfileBean {
private String name;
private String number;
public boolean isChecked;
// private boolean checked = false ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public ProfileBean(String name, String number) {
super();
this.name = name;
this.number = number;
}
}
And keep remaining same..try like this and let know if any problem..
Change your onBkpress method like this..
#Override
public void onBackPressed() {
phno0.clear();
for (ProfileBean bean : list) {
if (bean.isChecked) {
phno0.add(bean.getNumber());
} else {
System.out.println("..Not Checked......"
+ list.get(i).getNumber().toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
}

Related

Image not match item in listview when search with SearchView Android

I have listview in fragment populated from Activity with bundle , i have custom baseadapter and custom object with image and text , listview work fine with image and text , but when i do search with searchview i can get text and it's position and onclicklistener is ok without any problem, the issue is that i can't have image(logos ) with the correcte item(texttitle) , images is ranged by it's own position and not item text position
First here is my Custom object
public class Channel {
public String name;
public String logoUrl;
public Channel(String name, String logoUrl) {
this.name = name;
this.logoUrl = logoUrl;
}
#Override
public String toString() {
return "Channel {" +
"name='" + name + '\'' +
", logoUrl='" + logoUrl + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
}
and here is my custom Base Adapter
public class ChannelAdapter extends BaseAdapter implements Filterable{
private Activity context;
private ArrayList<Channel> channelNames = new ArrayList<>(); //mList
private ArrayList<Channel> channelLogos = new ArrayList<>();
private ArrayList<Channel> tmpNames= null;
private ArrayList<Channel> tmpLogos= null;
private CustomFilter myFilter = new CustomFilter();
ColorSpace.Model model;
public ChannelAdapter(Context context, ArrayList<Channel> channels, ArrayList<Channel> logos){
this.context = (Activity) context;
this.channelNames = channels;
this.channelLogos = logos;
this.tmpNames = channels;
this.tmpLogos = logos;
// Names.addAll(channelLogos);
}
#Override
public int getCount() {
// return Names.size();
return tmpNames.size();
}
#Override
public String getItem(int position) {
return String.valueOf(tmpNames.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =null;
if(convertView==null) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.custom_row,parent, Boolean.parseBoolean(null));
}else{
row=convertView;
}
TextView textView= (TextView) row.findViewById(R.id.textv);
ImageView image=(ImageView) row.findViewById(R.id.imageView);
textView.setText((CharSequence) tmpNames.get(position));
Picasso.with(context)
.load(String.valueOf(tmpLogos.get(position)))
.into(image);
return row;
}
#Override
public Filter getFilter() {
if (myFilter == null) {
myFilter = new CustomFilter();
}
return myFilter;
}
public class CustomFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final ArrayList<Channel> list = channelNames; //remettre channelNames
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = String.valueOf(list.get(i));
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
// Names.clear();
// addAll((List<Channel>) results.values);
tmpNames = (ArrayList<Channel>) results.values;
notifyDataSetChanged();
}
}
}
and finaly my OnqueryTextChange
#Override
public boolean onQueryTextChange(String newText) {
((ChannelAdapter)listView.getAdapter()).getFilter().filter(newText.toString());
}
});
Please need help if possible and thank's in advance
here is my adapter class
public class ChannelAdapter extends MatchableArrayAdapter<Channel>{
private Activity context;
private ArrayList<Channel> channelNames = new ArrayList<>(); //mList
private ArrayList<Channel> channelLogos = new ArrayList<>();
private ArrayList<Channel> tmpNames= new ArrayList<Channel>();
private ArrayList<Channel> tmpLogos= null;
boolean notifyChanged = false;
public ChannelAdapter(Context context, ArrayList<Channel> channels,
ArrayList<Channel> logos){
super(context, 0, channels);
this.context = (Activity) context;
this.channelNames = channels;
this.channelLogos = logos;
this.tmpNames = channels;
this.tmpLogos = channels;
// Names.addAll(channelLogos);
}
#Override
public int getCount() {
// return Names.size();
return channelNames.size();
}
#Override
public Channel getItem(int position) {
return channelNames.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =null;
if(convertView==null) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.custom_row,parent, Boolean.parseBoolean(null));
}else{
row=convertView;
}
// TextView textView = null;
TextView textView= (TextView) row.findViewById(R.id.textv);
// ((TextView)row.findViewById(R.id.textv)).getText().toString();
ImageView image=(ImageView) row.findViewById(R.id.imageView);
textView.setText((CharSequence) channelNames.get(position));
Picasso.with(context)
.load(String.valueOf(channelLogos.get(position)))
.into(image);
return row;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Channel> results = new ArrayList<Channel>();
if (channelNames == null)
channelNames = tmpNames;
if (constraint != null) {
if (channelNames != null && channelNames.size() > 0) {
for (final Channel g : channelNames) {
if (g.getName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
tmpNames = (ArrayList<Channel>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
notifyChanged = true;
}
}
public class Channel {
private String name;
private String logoUrl;
public Channel(String name, String logoUrl) {
this.name = name;
this.logoUrl = logoUrl;
}
#Override
public String toString() {
return "Channel{" +
"name='" + name + '\'' +
", logoUrl='" + logoUrl + '\'' +
'}';
}
public String getName() {
return String.valueOf(name);
}
public void setName(ArrayList<String> name) {
this.name = String.valueOf(name);
}
public String getLogoUrl() {
return String.valueOf(logoUrl);
}
public void setLogoUrl(ArrayList<String> logoUrl) {
this.logoUrl = String.valueOf(logoUrl);
}
}
public class ChannelAdapter extends MatchableArrayAdapter<Channel> {
public ChannelAdapter(Context context, List<Channel> objects) {
super(context, R.layout.custom_row, objects);
}
#Override
protected void onBind(Channel item, View itemView, int position) {
TextView tv = (TextView) itemView.findViewById(R.id.textv);
tv.setText(item.getName());
ImageView iv = (ImageView) itemView.findViewById(R.id.imageView);
Picasso.with(iv.getContext())
.load(item.getLogoUrl())
.into(iv);
}
#Override
protected boolean matches(Channel value, CharSequence constraint,
CharSequence lowerCaseConstraint) {
return value.getName().toLowerCase().contains(lowerCaseConstraint);
}
}

Unable to filter data Product Name wise in android

this is my adapter class:
public class Searchlistviewadapter extends ArrayAdapter<DataModel> implements
Filterable {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<DataModel> datamodel;
ArrayList<DataModel> productlist;
private ProductFilter filter;
private SparseBooleanArray mSelectedItemsIds;
MyDatabaseHelper dbhelper;
int counter;
int Quantity = 0;
HashMap<Integer, Integer> hashMap;
int searchBy = 0;
static final String TAG = "LISTT";
List<DataModel> listDatamodels = new ArrayList<DataModel>();
public Searchlistviewadapter(Context context, int resourceId,
ArrayList<DataModel> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.datamodel = worldpopulationlist;
inflater = LayoutInflater.from(context);
dbhelper = new MyDatabaseHelper(context);
productlist = worldpopulationlist;
hashMap = new HashMap<Integer, Integer>();
}
private class ViewHolder {
TextView tv;
TextView Quantity;
TextView cost;
ImageView img;
ImageView plusitem;
ImageView minusitem;
TextView itemnumber;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listitem, null);
//
holder.tv = (TextView) view.findViewById(R.id.textView1);
holder.img = (ImageView) view.findViewById(R.id.imageView1);
holder.Quantity = (TextView) view.findViewById(R.id.textView3);
holder.cost = (TextView) view.findViewById(R.id.textView2);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
String rupee = context.getResources().getString(R.string.Rs);
final MyDatabaseHelper dbManager = new MyDatabaseHelper(context);
dbManager.open();
holder.tv.setText(datamodel.get(position).getProductname());
holder.Quantity.setText(datamodel.get(position).getProdcutQuantity());
holder.cost.setText(rupee + datamodel.get(position).getProdcutCost());
holder.img.setImageResource(datamodel.get(position).getProductimage());
holder.plusitem = (ImageView) view.findViewById(R.id.imageButton2);
holder.plusitem.setTag(position);
holder.minusitem = (ImageView) view.findViewById(R.id.imageButton);
holder.minusitem.setTag(position);
holder.itemnumber = (TextView) view.findViewById(R.id.textView4);
holder.plusitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int index = Integer.parseInt(arg0.getTag().toString());
Log.e(TAG, Integer.toString(index));
int quantity;
if (hashMap.containsKey(index)) {
quantity = hashMap.get(index);
} else
quantity = 0;
quantity++;
hashMap.put(index, quantity);
holder.itemnumber.setText(quantity + "");
// holder.itemnumber.invalidate();
dbhelper.open();
String producttype = dbhelper.getCteogryusingId(datamodel.get(
position).getProdcutid());
dbManager.AddShopingItem(
datamodel.get(position).getProdcutid(), producttype,
datamodel.get(position).getProductname(), datamodel
.get(position).getProdcutQuantity(), datamodel
.get(position).getProdcutCost(), String
.valueOf(datamodel.get(position)
.getProductimage()), String
.valueOf(quantity), "true");
sendBroadcaset(true);
}
});
holder.minusitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index = Integer.parseInt(v.getTag().toString());
Log.e(TAG, Integer.toString(index));
int quantity;
if (hashMap.containsKey(index)) {
quantity = hashMap.get(index);
} else
quantity = 0;
quantity--;
if (quantity < 0)
quantity = 0;
hashMap.put(index, quantity);
holder.itemnumber.setText(quantity + "");
// holder.itemnumber.invalidate();
dbhelper.open();
String producttype = dbhelper.getCteogryusingId(datamodel.get(
position).getProdcutid());
dbManager.AddShopingItem(
datamodel.get(position).getProdcutid(), producttype,
datamodel.get(position).getProductname(), datamodel
.get(position).getProdcutQuantity(), datamodel
.get(position).getProdcutCost(), String
.valueOf(datamodel.get(position)
.getProductimage()), String
.valueOf(quantity), "true");
sendBroadcaset(false);
}
});
return view;
}
private void sendBroadcaset(boolean b) {
// TODO Auto-generated method stub
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent("update_boolean_variable").putExtra("action", b));
}
private class ProductFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
ArrayList<DataModel> filteredItems = new ArrayList<DataModel>();
for (int i = 0, l = datamodel.size(); i < l; i++) {
DataModel country = datamodel.get(i);
if (country.getProductname().toString().toLowerCase()
.contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
} else {
synchronized (this) {
result.values = datamodel;
result.count = datamodel.size();
}
}
return result;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
productlist = (ArrayList<DataModel>) results.values;
notifyDataSetChanged();
clear();
for (int i = 0, l = productlist.size(); i < l; i++)
add(productlist.get(i));
notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new ProductFilter();
}
return filter;
}
}
this is my activity claSS:
public class MainActivity extends Activity implements View.OnClickListener {
ImageView backbutton;
private ListView lv;
Searchlistviewadapter listviewadapter;
EditText inputSearch;
ArrayList<HashMap<String, String>> productList;
MyDatabaseHelper dbhelper;
public static final int img2 = R.drawable.asirwadatata;
public static final int img3 = R.drawable.asirwadatata;
public static final int img4 = R.drawable.asirwadatata;
public static final int img5 = R.drawable.asirwadatata;
public static final int img6 = R.drawable.asirwadatata;
public static final int img7 = R.drawable.asirwadatata;
ArrayList<DataModel> lstDataModel;
public static final int[] images = new int[] { img2, img3, img4, img5,
img6, img7 };
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelper = new MyDatabaseHelper(MainActivity.this);
dbhelper.open();
String ProductId[] = dbhelper.getAllProductID();
dbhelper.open();
String products[] = dbhelper.getAllProductName();
dbhelper.open();
String productsquant[] = dbhelper.getAllProductQuntity();
dbhelper.open();
String productcost[] = dbhelper.getAllProductCost();
lv = (ListView) findViewById(R.id.listView1);
inputSearch = (EditText) findViewById(R.id.inputSearch);
lstDataModel = new ArrayList<DataModel>();
for (int i = 0; i < products.length; i++) {
DataModel datamodel = new DataModel();
datamodel.setProdcutid(ProductId[i]);
datamodel.setProductname(products[i]);
datamodel.setProdcutQuantity(productsquant[i]);
datamodel.setProdcutCost(productcost[i]);
datamodel.setProductimage(images[i]);
lstDataModel.add(datamodel);
}
listviewadapter = new Searchlistviewadapter(MainActivity.this,
R.layout.listitem, lstDataModel);
lv.setAdapter(listviewadapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
System.out.println("Text [" + cs + "]");
listviewadapter.getFilter().filter(cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v) {
}
}
DataModel:
public class DataModel {
public String getProdcutid() {
return prodcutid;
}
public void setProdcutid(String prodcutid) {
this.prodcutid = prodcutid;
}
private String prodcutid;
private String Cateogry;
private String Productname;
private String ProdcutQuantity;
private int Productimage;
private String ProdcutCost;
private String NuberofProductQuantity;
public String eachProdcutcount;
public String getEachProdcutcount() {
return eachProdcutcount;
}
public void setEachProdcutcount(String eachProdcutcount) {
this.eachProdcutcount = eachProdcutcount;
}
public DataModel() {
// TODO Auto-generated constructor stub
}
public DataModel(String productname, String prodcutQuantity,
int productimage) {
super();
this.Productname = productname;
this.ProdcutQuantity = prodcutQuantity;
this.Productimage = productimage;
}
public String getCateogry() {
return Cateogry;
}
public void setCateogry(String cateogry) {
Cateogry = cateogry;
}
public String getProductname() {
return Productname;
}
public void setProductname(String productname) {
Productname = productname;
}
public String getProdcutQuantity() {
return ProdcutQuantity;
}
public void setProdcutQuantity(String prodcutQuantity) {
ProdcutQuantity = prodcutQuantity;
}
public int getProductimage() {
return Productimage;
}
public void setProductimage(int productimage) {
Productimage = productimage;
}
public String getProdcutCost() {
return ProdcutCost;
}
public void setProdcutCost(String prodcutCost) {
ProdcutCost = prodcutCost;
}
public String getNuberofProductQuantity() {
return NuberofProductQuantity;
}
public void setNuberofProductQuantity(String nuberofProductQuantity) {
NuberofProductQuantity = nuberofProductQuantity;
}
i am trying to filter or Search item from Listview i am able to filter data But Problem when i clear data i mean when we blank data after filtering from Edit text then my listview item becomes blank again we have launch app and then item listview item becomes visible please tell me where am doing wrong please suggest me .
I have changed your adapter class ..please try with below class
public class Searchlistviewadapter extends ArrayAdapter<DataModel> implements
Filterable {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<DataModel> datamodel;
ArrayList<DataModel> productlist;
private ProductFilter filter;
private SparseBooleanArray mSelectedItemsIds;
MyDatabaseHelper dbhelper;
int counter;
int Quantity = 0;
HashMap<Integer, Integer> hashMap;
int searchBy = 0;
static final String TAG = "LISTT";
List<DataModel> listDatamodels = new ArrayList<DataModel>();
public Searchlistviewadapter(Context context, int resourceId,
ArrayList<DataModel> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
// this.datamodel = worldpopulationlist;
this.datamodel = new ArrayList<DataModel>();
// productlist = worldpopulationlist;
this.datamodel.addAll(worldpopulationlist);
inflater = LayoutInflater.from(context);
dbhelper = new MyDatabaseHelper(context);
productlist = new ArrayList<DataModel>();
// productlist = worldpopulationlist;
productlist.addAll(worldpopulationlist);
hashMap = new HashMap<Integer, Integer>();
}
private class ViewHolder {
TextView tv;
TextView Quantity;
TextView cost;
ImageView img;
ImageView plusitem;
ImageView minusitem;
TextView itemnumber;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listitem, null);
//
holder.tv = (TextView) view.findViewById(R.id.textView1);
holder.img = (ImageView) view.findViewById(R.id.imageView1);
holder.Quantity = (TextView) view.findViewById(R.id.textView3);
holder.cost = (TextView) view.findViewById(R.id.textView2);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
String rupee = context.getResources().getString(R.string.Rs);
final MyDatabaseHelper dbManager = new MyDatabaseHelper(context);
dbManager.open();
holder.tv.setText(datamodel.get(position).getProductname());
holder.Quantity.setText(datamodel.get(position).getProdcutQuantity());
holder.cost.setText(rupee + datamodel.get(position).getProdcutCost());
holder.img.setImageResource(datamodel.get(position).getProductimage());
holder.plusitem = (ImageView) view.findViewById(R.id.imageButton2);
holder.plusitem.setTag(position);
holder.minusitem = (ImageView) view.findViewById(R.id.imageButton);
holder.minusitem.setTag(position);
holder.itemnumber = (TextView) view.findViewById(R.id.textView4);
holder.plusitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int index = Integer.parseInt(arg0.getTag().toString());
Log.e(TAG, Integer.toString(index));
int quantity;
if (hashMap.containsKey(index)) {
quantity = hashMap.get(index);
} else
quantity = 0;
quantity++;
hashMap.put(index, quantity);
holder.itemnumber.setText(quantity + "");
// holder.itemnumber.invalidate();
dbhelper.open();
String producttype = dbhelper.getCteogryusingId(datamodel.get(
position).getProdcutid());
dbManager.AddShopingItem(
datamodel.get(position).getProdcutid(), producttype,
datamodel.get(position).getProductname(), datamodel
.get(position).getProdcutQuantity(), datamodel
.get(position).getProdcutCost(), String
.valueOf(datamodel.get(position)
.getProductimage()), String
.valueOf(quantity), "true");
sendBroadcaset(true);
}
});
holder.minusitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index = Integer.parseInt(v.getTag().toString());
Log.e(TAG, Integer.toString(index));
int quantity;
if (hashMap.containsKey(index)) {
quantity = hashMap.get(index);
} else
quantity = 0;
quantity--;
if (quantity < 0)
quantity = 0;
hashMap.put(index, quantity);
holder.itemnumber.setText(quantity + "");
// holder.itemnumber.invalidate();
dbhelper.open();
String producttype = dbhelper.getCteogryusingId(datamodel.get(
position).getProdcutid());
dbManager.AddShopingItem(
datamodel.get(position).getProdcutid(), producttype,
datamodel.get(position).getProductname(), datamodel
.get(position).getProdcutQuantity(), datamodel
.get(position).getProdcutCost(), String
.valueOf(datamodel.get(position)
.getProductimage()), String
.valueOf(quantity), "true");
sendBroadcaset(false);
}
});
return view;
}
private void sendBroadcaset(boolean b) {
// TODO Auto-generated method stub
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent("update_boolean_variable").putExtra("action", b));
}
private class ProductFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = null;
try {
String filterString = constraint.toString().toLowerCase();
results = new FilterResults();
List<DataModel> list = productlist;
ArrayList<DataModel> nlist = new ArrayList<DataModel>();
if (constraint != null && constraint.toString().length() > 0) {
for (int i = 0; i < productlist.size(); i++) {
DataModel filterableString = list.get(i);
if (filterableString.getProductname().toString()
.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
} else {
synchronized (this) {
results.values = datamodel;
results.count = datamodel.size();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
try {
datamodel = (ArrayList<DataModel>) results.values;
notifyDataSetChanged();
clear();
for (int i = 0, l = datamodel.size(); i < l; i++)
add(datamodel.get(i));
notifyDataSetInvalidated();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new ProductFilter();
}
return filter;
}
}

Loading the filtered items to search output

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

Listview search with custom adapter not showing search results properly

Searching in Listview are not working properly. If i enter string that is in my array list it shows all the records but if i enter any other string in my edit text field it shows an empty list.
public class GetCustomList extends ListActivity {
TweetListAdaptor myAdaptor;
ListView lv;
EditText searchTxt;
public ArrayList<Contact> tweets = new ArrayList<Contact>();
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customer_info);
tweets = db.getAllContacts();
lv = (ListView) findViewById(android.R.id.list);
lv.setTextFilterEnabled(true);
searchTxt = (EditText) findViewById(R.id.editTextSearchNameField);
searchTxt.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
myAdaptor.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Button btnSearch = (Button) findViewById(R.id.buttonSearch);
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onPostExecute(null);
}
});
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("786","zahid", "bilaltown", '0'));
db.addContact(new Contact("123","Shahid", "bilaltown", '0'));
db.addContact(new Contact("123","waqas", "bilaltown", '0'));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
for (Contact cn : tweets) {
String log = "Id: "+cn.get_id()+ ",Code:"+ cn.get_code() +" ,Name: " + cn.get_name() + " ,Address: " + cn.get_address() + " ,Phone: " + cn.get_limit();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
protected void onPostExecute(Void result) {
myAdaptor = new TweetListAdaptor(GetCustomList.this, tweets);
myAdaptor.notifyDataSetChanged();
setListAdapter(myAdaptor);
}
public class TweetListAdaptor extends ArrayAdapter<Contact> implements Filterable {
private ArrayList<Contact> mOriginalValues = new ArrayList<Contact>(); // Original Values
private ArrayList<Contact> mDisplayedValues = new ArrayList<Contact>(); // Values to be displayed
LayoutInflater inflater;
Context context;
public TweetListAdaptor(Context context,ArrayList<Contact> items) {
super(context, R.layout.custom_list_info, items);
this.mOriginalValues = items;
this.mDisplayedValues = items;
this.context = context;
// inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mDisplayedValues.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
private TextView CustomerId;
private TextView CustomerShop;
private TextView date;
private TextView phoneNumber;
public ViewHolder(View v) {
this.CustomerId = (TextView) v.findViewById(R.id.textViewCustomerID);
this.CustomerShop = (TextView) v.findViewById(R.id.textViewShopName);
// this.date = (TextView) v.findViewById(R.id.date);
// this.status = (TextView) v.findViewById(R.id.staus);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.custom_list_info, null);
holder = new ViewHolder(v);
v.setTag(holder);
}else {
holder = (ViewHolder) v.getTag();
}
final Contact o = getItem(position);
if (o != null) {
holder.CustomerId.setText(""+o._id);
holder.CustomerShop.setText(o._name);
//holder.date.setText(o.date);
//holder.status.setText(o.status_txt);
/*if(o.status.equals("1")){
RelativeLayout llr = (RelativeLayout) v.findViewById(R.id.testRes);
llr.setBackgroundResource(R.drawable.decline);
}else if(o.status.equals("2")){
RelativeLayout llr = (RelativeLayout) v.findViewById(R.id.testRes);
llr.setBackgroundResource(R.drawable.acceptence);
}
}*/
ImageButton btnSearchCustomer = (ImageButton) v.findViewById(R.id.btnSearchCustomer);
btnSearchCustomer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(GetCustomList.this, CustomerDetailedInfo.class);
intent.putExtra("ccode", o._code);
intent.putExtra("cname", o._name);
intent.putExtra("caddress", o._address);
intent.putExtra("climit", o._limit);
startActivity(intent);
}
});
}
return v;
}
///////////////////////////////
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
mDisplayedValues = (ArrayList<Contact>) 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
ArrayList<Contact> FilteredArrList = new ArrayList<Contact>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<Contact>(mDisplayedValues); // 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)._name;
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(new Contact(mOriginalValues.get(i)._name,mOriginalValues.get(i)._code,mOriginalValues.get(i)._address,mOriginalValues.get(i)._limit));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
///////////////////
}
Contact class
public class Contact {
//private variables
int _id;
String _code;
String _name;
String _address;
int _limit;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String _code,String name,String address, int _limit){
this._id = id;
this._code = _code;
this._name = name;
this._address = address;
this._limit = _limit;
}
// constructor
public Contact(String _code,String name, String address,int _limit){
this._code = _code;
this._name = name;
this._address = address;
this._limit = _limit;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_code() {
return _code;
}
public void set_code(String _code) {
this._code = _code;
}
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
}
public String get_address() {
return _address;
}
public void set_address(String _address) {
this._address = _address;
}
public int get_limit() {
return _limit;
}
public void set_limit(int _limit) {
this._limit = _limit;
}
}
There are a couple of minor mistakes in the code. First, you need to override the getItem() method in TweetListAdaptor:
#Override
public Contact getItem(int position)
{
return mDisplayedValues.get(position);
}
Then, in the Filter's performFiltering() method, the code and name parameters are switched for the Contact constructor in the following line:
FilteredArrList.add(new Contact(mOriginalValues.get(i)._code, mOriginalValues.get(i)._name, mOriginalValues.get(i)._address, mOriginalValues.get(i)._limit));
I ran a test with 20 names, and I believe that those corrections should fix the problem.

how to get the checked contacts details in a string

i want to get the contact numbers in a string when user checked the contact,after which onBackpress the selected values can be stored in database.user can select multiple contacts at a time and when user returns back on the activity,the check box remains checked, so that he can see his selected contacts.
MainActivity
public class MainActivity extends Activity {
String[] cellArray = null;
String contacts;
String phoneNumber, name;
ArrayList<String> phno0 = new ArrayList<String>();
StringBuilder b = new StringBuilder();
//private ArrayAdapter<String> adapter;
List<String> arrayListNames;
private ListView listview;
private EditText edittext;
private List<ProfileBean> list;
private SearchableAdapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
edittext = (EditText) findViewById(R.id.edittext);
list = new ArrayList<ProfileBean>();
getAllCallLogs(this.getContentResolver());
adapter = new SearchableAdapter(getApplicationContext(), list);
listview.setAdapter(adapter);
edittext.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
}
#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.toString());
}
});
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ProfileBean bean = (ProfileBean) arg1.getTag();
Toast.makeText(getApplicationContext(), bean.getName(), Toast.LENGTH_LONG).show();
}
});
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
list.add(new ProfileBean(name, phoneNumber));
}
}
}
Adapterclass
public class SearchableAdapter extends BaseAdapter implements Filterable, OnCheckedChangeListener {
private List<ProfileBean>originalData = null;
private List<ProfileBean>filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<ProfileBean> data) {
//mCheckStates = new SparseBooleanArray(filteredData.size());
this.filteredData = data ;
this.originalData = data ;
mInflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.lname = (TextView) convertView.findViewById(R.id.lname);
holder.no = (CheckBox) convertView.findViewById(R.id.no);
holder.no.setTag(position);
holder.no.setOnCheckedChangeListener(this);
convertView.setTag(R.layout.list_item,holder);
} else {
holder = (ViewHolder) convertView.getTag(R.layout.list_item);
}
ProfileBean bean = filteredData.get(position);
holder.name.setText(bean.getName());
holder.lname.setText(bean.getLname());
convertView.setTag(bean);
return convertView;
}
static class ViewHolder {
TextView name;
TextView lname;
CheckBox no;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<ProfileBean> list = originalData;
int count = list.size();
final ArrayList<ProfileBean> nlist = new ArrayList<ProfileBean>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
ProfileBean bean = list.get(i);
filterableString = bean.getName();
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(bean);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
BeanClass
package com.example.mylistviewtest;
public class ProfileBean {
private String name;
private String lname;
private boolean checked = false ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public ProfileBean(String name, String lname) {
super();
this.name = name;
this.lname = lname;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public void toggleChecked() {
checked = !checked ;
}
}

Categories

Resources