how to get the checked contacts details in a string - android

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

Related

handle list view with check box and search implemention

i have a list view which has check box on each row and i`ve implemented a serch view to search in the list view. the problem is that when i search the list view and select item at postion X from the modifided list, delete the text from the search view i see the original list with the item checked in position X.
Example - list of a,b,c....z .
i can see 5 items on the list:
A
B
C
D
E
then search for z so i see only Z and check it. then i delete Z and see A-E again and A is checked.
this is my main:
public class AddRoomatesScreen extends Activity implements AdapterView.OnItemClickListener,SearchView.OnQueryTextListener {
SharedPreferences preferences;
List<String> nameList = new ArrayList<String>();
List<String> phoneList = new ArrayList<String>();
MyAdapter adapter;
Button btnSelect;
String apartmentnumber;
SearchView searchView;
ArrayList<Contact> contactList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_roomate);
preferences = getSharedPreferences("appData", 0);
int apartmentNumber = preferences.getInt("apartmentNumber", 0);
apartmentnumber = Integer.toString(apartmentNumber);
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
adapter = new MyAdapter(nameList,contactList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
searchView = (SearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(this);
// adding
btnSelect = (Button) findViewById(R.id.addSelectedContacts);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i<adapter.mCheckStates.size(); i++){
Contact contact = (adapter.contactsListCopy.get(adapter.mCheckStates.keyAt(i)));
new addRoommate().execute(apartmentnumber, contact.getPhoneNumber());
}
preferences = getSharedPreferences("appData", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("roomatesLoadedFromDB", false);
editor.apply();
}
});
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
adapter.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
nameList.add(name);
phoneList.add(phoneNumber);
contactList.add(new Contact(name,phoneNumber));
}
phones.close();
}
this is my adapter:
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener,Filterable {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv;
CheckBox cb;
ValueFilter filter;
ArrayList<Contact> contactsList;
ArrayList<Contact> contactsListCopy;
MyAdapter(List<String> nameList , ArrayList<Contact> contactsList) {
mCheckStates = new SparseBooleanArray(contactsList.size());
mInflater = (LayoutInflater) AddRoomatesScreen.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.contactsList = contactsList;
this.contactsListCopy = this.contactsList;
getFilter();
}
#Override
public int getCount() {
return contactsListCopy.size();
}
#Override
public Object getItem(int position) {
return contactsListCopy.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.contact_list_item, null);
TextView tv = (TextView) vi.findViewById(R.id.textView3);
cb = (CheckBox) vi.findViewById(R.id.checkBox);
Contact contact = contactsListCopy.get(position);
tv.setText(contact.getName());
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new ValueFilter();
}
return filter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Contact> temp = new ArrayList<Contact>();
for (int i = 0; i < contactList.size(); i++) {
Contact c = contactList.get(i);
if ((c.getName().toString())
.contains(constraint.toString())) {
temp.add(c);
}
}
results.count = temp.size();
results.values = temp;
} else {
results.count = contactList.size();
results.values = contactList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
contactsListCopy = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
}
this is my model:
public class Contact{
private String phoneNumber;
private String name;
public Contact(String name , String phoneNumber){
this.phoneNumber = phoneNumber;
this.name = name;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
EDIT:
You can use the ID from the cursor as your unique id.
This code would go with the code originally posted below.
Add id to your Contact class:
public class Contact{
private long id;
private String phoneNumber;
private String name;
public Contact(long id, String name , String phoneNumber) {
this.id = id;
this.phoneNumber = phoneNumber;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
This is how you get the ID from the cursor:
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
long id = phones.getLong(phones.getColumnIndex(ContactsContract.Data._ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
nameList.add(name);
phoneList.add(phoneNumber);
contactList.add(new Contact(id, name, phoneNumber));
}
phones.close();
}
Your mCheckStates in the adapter changes to:
private LongSparseArray<Boolean> mCheckStates;
Some of the original answer below has been changed to match the long type used for id.
The problem is that your mCheckStates boolean map isn't kept in sync with contactsListCopy as it is filtered.
You filtered on Z so Z is now item 0,
You checked Z which sets position 0 as checked,
You redisplay the whole list. Now A is position 0 so it shows as checked.
Instead of tracking checked positions, you need to track checked contacts. To do that, you need to use the unique ID from the contact record.
Here's the changes you need to make:
Make your adapter use the unique id:
#Override
public long getItemId(int position) {
return contactsListCopy.get(position).getId();
}
Now your activity has to use the unique id instead of position:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
adapter.toggle(arg3);
}
In your adapter getView(), you have to use the ID for the check box now
cb.setTag(contact.getId());
cb.setChecked(mCheckStates.get(contact.getId(), false));
I would change some other methods just to avoid confusion:
public boolean isChecked(long id) {
return mCheckStates.get(id, false);
}
public void setChecked(long id, boolean isChecked) {
mCheckStates.put(id, isChecked);
notifyDataSetChanged();
}
public void toggle(long id) {
setChecked(id, !isChecked(id));
}

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

position of checkbox get change

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

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.

Categories

Resources