Search code examples
javaandroidarrayslibphonenumberphonenumberutils

How to get PhoneNumberUtil to recognize arrays?


I have a list of contacts in a recyclerview with phone numbers. I want PhoneNumberUtil (libphonenumber) to tell me whether one of those contacts is calling by comparing the incoming number with numbers in the list. At the moment, this works only with contacts that only have one phone number. What I want is for it to work with contacts that have several numbers too.

This is part of my code:

String listNumbers = listItem.getNumbers().toString();

                System.out.println(listNumbers);

                PhoneNumberUtil pnu = PhoneNumberUtil.getInstance();

                PhoneNumberUtil.MatchType mt = pnu.isNumberMatch(listNumbers, number);
                if (mt == PhoneNumberUtil.MatchType.NSN_MATCH || mt == PhoneNumberUtil.MatchType.SHORT_NSN_MATCH || mt == PhoneNumberUtil.MatchType.EXACT_MATCH) {
                    if (selected) {
                        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                        if (notificationManager != null) {
                            notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
                        }
                    }
                }

This is what my System Out looks like:

I/System.out: [029-426-9301, 029-426-9302, 029-426-9303]
I/System.out: [044-070-2586]
I/System.out: [225-649-86, 225-649-86]
I/System.out: [078-885-21174]

What I have tried:

I have tried formatting the String arrays so that commas would be replaced by square brackets, like this: [029-426-9301] [029-426-9302] [029-426-9303]. However, this made no difference, the numbers were still not recognised.

I would be grateful for some suggestions.


Solution

  • You could do something like this:

    boolean isMatch = false;
    String matchedNumber = null;
    
    for (String currentNumber : listItem.getNumbers ()) {
        PhoneNumberUtil.MatchType mt = pnu.isNumberMatch (currentNumber, number);
        if (mt == PhoneNumberUtil.MatchType.NSN_MATCH || mt == PhoneNumberUtil.MatchType.SHORT_NSN_MATCH || mt == PhoneNumberUtil.MatchType.EXACT_MATCH) {
            isMatch = true;
            matchedNumber = currentNumber;
    
            break;
        }
    }
    
    if (isMatch) {
        // your business logic
    }