Search code examples
androidrealm

Realm Android DB Filtering


I am using RealmDB as my Android Local Storage. But, filtering is not working fine for me. E.g: If I've GOOGLE in the DB if I query for google it wouldn't show it up. If I've Google if I query for google same thing. Unless the name is well typed. I've tried to lower case my own result to filter. All to no avail. I extend a BaseAdapter to use in my AutoCompleteTextView.

    @Override
    public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            return null;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults filterResults) {
            if (constraint != null) {
                //String query = constraint.toString().toLowerCase();
                mResult = filterStates(constraint.toString());
                Log.e(TAG, "" + mResult.size());
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    };
    }

    @NonNull
    private List<RealmOutlet> filterStates(String query) {
    Realm mRealm = RealmUtils.getRealmInstance(mContext);
    return mRealm.where(RealmOutlet.class)
            /*.equalTo("channel", "distributor")
            .equalTo("isSent", true)*/
            .beginGroup()
            .equalTo("name", query)
            .or()
            .contains("name", query)
            .or()
            .beginsWith("name", query)
            .endGroup()
            .findAll();
    }

Solution

  • Considering this seems to be the same code as https://gist.github.com/sdex/83b75ce9c2f2e2654bec , I think it should work if you replace

    @NonNull
    private List<RealmOutlet> filterStates(String query) {
    Realm mRealm = RealmUtils.getRealmInstance(mContext);
    return mRealm.where(RealmOutlet.class)
            /*.equalTo("channel", "distributor")
            .equalTo("isSent", true)*/
            .beginGroup()
            .equalTo("name", query)
            .or()
            .contains("name", query)
            .or()
            .beginsWith("name", query)
            .endGroup()
            .findAll();
    }
    

    with

    @NonNull
    private List<RealmOutlet> filterStates(String query) {
    Realm mRealm = RealmUtils.getRealmInstance(mContext);
    return mRealm.where(RealmOutlet.class)
            .contains("name", query, Case.INSENSITIVE)
            .findAll();
    }
    

    Although opening a new instance over and over again is bad practice.