How to use SearchView with filter mode in ListView in API 8

I am developing Android with minSdkVersion 8

and am using ListView to display mobile contacts in my application, but now I need to add a filter to view the list, but I cannot find one to use SearchView

in sdkVersion 8

can you guys help. here is my code -

ArrayList<String> names = new ArrayList<String>();
ArrayList<String> phones = new ArrayList<String>();
ArrayList<String[]> selectedPhones = new ArrayList<String[]>();
ArrayList<String> selectedPhoneNumbers = new ArrayList<String>();

MyAdapter adapter;
Button done;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contacts);
    ArrayList<String[]> oldContacts = (ArrayList<String[]>) getIntent()
            .getSerializableExtra("contacts");
    for (int i = 0; i < oldContacts.size(); i++) {
        selectedPhoneNumbers.add(oldContacts.get(i)[1]);
    }
    getAllCallLogs(this.getContentResolver());
    ListView lv = (ListView) findViewById(R.id.lvContactsSelecetion);
    adapter = new MyAdapter();
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(this);
    lv.setItemsCanFocus(false);
    lv.setTextFilterEnabled(true);
    done = (Button) findViewById(R.id.bSelectContacts);
    done.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            for (int i = 0; i < names.size(); i++) {
                if (adapter.mCheckStates.get(i) == true) {
                    String[] contact = new String[] {
                            names.get(i).toString(),
                            phones.get(i).toString() };
                    selectedPhones.add(contact);
                }
            }
            Intent returnIntent = new Intent();
            returnIntent.putExtra("contacts", selectedPhones);
            setResult(RESULT_OK, returnIntent);
            finish();
        }
    });
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    adapter.toggle(arg2);
}

public void getAllCallLogs(ContentResolver cr) {
    Cursor contacts = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, "DISPLAY_NAME ASC");
    while (contacts.moveToNext()) {
        String name = contacts
                .getString(contacts
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = contacts
                .getString(contacts
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        names.add(name);
        phones.add(phoneNumber);
    }

    contacts.close();
}

class MyAdapter extends BaseAdapter implements
        CompoundButton.OnCheckedChangeListener {

    private SparseBooleanArray mCheckStates;
    LayoutInflater mInflater;
    TextView tv1, tv;
    CheckBox cb;

    MyAdapter() {
        mCheckStates = new SparseBooleanArray(names.size());
        mInflater = (LayoutInflater) Contacts.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return names.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView,
            ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = mInflater.inflate(R.layout.row_contact, null);
        tv = (TextView) vi.findViewById(R.id.tvContactName);
        tv1 = (TextView) vi.findViewById(R.id.tvContactNumber);
        cb = (CheckBox) vi.findViewById(R.id.cbContactSelected);
        tv.setText("Name :" + names.get(position));
        tv1.setText("Phone No :" + phones.get(position));
        cb.setTag(position);
        if (selectedPhoneNumbers.contains(phones.get(position)))
            cb.setChecked(mCheckStates.get(position, true));
        else
            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);
    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));
    }

    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        mCheckStates.put((Integer) buttonView.getTag(), isChecked);
    }
}

      

+3


source to share


2 answers


Simple steps:

  • Take a simple EditText
  • Apply a filter to it


Sample code:

yourEditSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                adapter.getFilter().filter(s);
            }
        };


class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener,  Filterable  {
       @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @Override
            protected void publishResults(CharSequence constraint,
                    FilterResults results) {

                // Now we have to inform the adapter about the new list filtered
                if (results.count == 0)
                     notifyDataSetInvalidated();
                else {
                    names= (ArrayList<String>) results.values;
                   notifyDataSetChanged();
                }
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {


                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();

               // check with the nane in list and add it
               //iterate and check with the matching string
               for (int i=0;i<names.size();i++) {
                    String dataNames = names.get(i);
                    if (dataNames.toLowerCase().contains(constraint.toString())) {
                         FilteredArrayNames.add(entity);
                  }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;

                return results;
            }
        };
        return filter;
    }

}

      

0


source


There is a class - this is a support library just for this:



SearchViewCompat

+1


source







All Articles