Android + ObjectBox Search Query Issue

334 views Asked by At

I am stuck with the ObjectBox Like Query. I have done as below when I search for something.

    QueryBuilder<MItemDetail> builder = mItemDetailListBox.query();
    builder.contains(MItemDetail_.productName, search);
    itemList = builder.build().find();

For example, My data is:

  1. paracetamol
  2. paracetamol potest
  3. paracetamol_new

Problem:

Now as you know the contains works simply as that returns a list of items that contain a given search string.

What I Want:

  • If I search para new, I want the result paracetamol_new

  • If I search para p, I want the result paracetamol potest

  • If I search para e e, I want the result paracetamol potest and paracetamol_new

Is there any function or utility available in ObjectBox that can help me to achieve this?

Do let me know If you have any questions.

Edited:

The given links in a comment, My question is different. I know all the methods contains(), startsWith, and endsWith but my problem not getting solved using that.

1

There are 1 answers

0
Pratik Butani On BEST ANSWER

With Reference to this answer I have done some changes as given and I got a perfect solution as I wanted.

QueryBuilder<MItemDetail> builder = mItemDetailListBox.query();
// builder.contains(MItemDetail_.productName, search);
builder.filter(new QueryFilter<MItemDetail>() {
    @Override
    public boolean keep(@NonNull MItemDetail entity) {
        return like(entity.getProductName(), "%"+ search + "%");
    }
}).order(MItemDetail_.productName);
businessModels = builder.build().find();

In the following methods, I have added one more replace statement .replace(" ",".*?")

private static boolean like(final String str, final String expr) {
    String safeString = (str == null) ? "" : str;
    String regex = quoteMeta(expr);
    regex = regex.replace("_", ".").replace(" ",".*?").replace("%", ".*?");
    Pattern p = Pattern.compile(regex,
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    return p.matcher(safeString).matches();
}

private static String quoteMeta(String s) {
    if (s == null) {
        throw new IllegalArgumentException("String cannot be null");
    }

    int len = s.length();
    if (len == 0) {
        return "";
    }

    StringBuilder sb = new StringBuilder(len * 2);
    for (int i = 0; i < len; i++) {
        char c = s.charAt(i);
        if ("[](){}.*+?$^|#\\".indexOf(c) != -1) {
            sb.append("\\");
        }
        sb.append(c);
    }
    return sb.toString();
}

Thank you.