Perform Search within a ListView with SimpleCursorAdapter

1

Good, I have the following code but it does not work and it does not throw me any errors, could you give me some guidance? , if anyone has encountered this problem. Thank you very much

 ListView mContactsList = (ListView) view.findViewById(R.id.listagenda);
      mContactsList.setAdapter(mAdapter);
      mContactsList.setTextFilterEnabled(true);
      mContactsList.setFastScrollEnabled(true);

    numpad.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            String text = numpad.getText().toString();
            Toast.makeText(getContext(),text,Toast.LENGTH_LONG).show();
            ContactsListActivity.this.mAdapter.getFilter().filter(text);


        }

        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {

        }

        public void afterTextChanged(Editable arg0) {
            ListView av = (ListView) view.findViewById(R.id.listagenda);
            SimpleCursorAdapter filterAdapter = (SimpleCursorAdapter)av.getAdapter();
            filterAdapter.getFilter().filter(arg0.toString());

        }
    });
    
asked by Fen Dev 21.06.2016 в 11:04
source

1 answer

1

I found the solution:

numpad.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {

            Log.d(null, "Filter:"+arg0);

                mAdapter.getFilter().filter(arg0);

        }

        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {

        }

        public void afterTextChanged(Editable arg0) {

        }
    });
    mAdapter.setFilterQueryProvider(new FilterQueryProvider() {

        public Cursor runQuery(CharSequence constraint) {
            Log.d(null, "runQuery constraint:"+constraint);
            //uri, projection, and sortOrder igual que antes
            //El selection debes cambiarlo segun la busqueda que quieras hacer con la variable constraint
            String SELECTIONS_SEARCH = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " like'%" + constraint + "%' OR "+ ContactsContract.CommonDataKinds.Phone.NUMBER + " like'%" + constraint + "%'";
            Cursor cur = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONE_PROJECTION, SELECTIONS_SEARCH, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY
                    + " COLLATE NOCASE ASC");
            return cur; //now your adapter will have the new filtered content
        }

    });
    
answered by 21.06.2016 / 16:54
source