Search code examples
androidautocompletespell-checking

Android get dictionary suggestions (equivalent to UiTextChecker)


I'm trying to implement some code in Android similar to code my colleague has written for iOS.

In his code he takes some input text and asks the system for autocomplete suggestions. The purpose is to guess what the next letter might be, so if the user has typed "pri" the possibilities might most likely be "c" (for "price"), "d" (for "pride"), "g" (for "prig") etc

Now my colleague uses an API in iOS called "UiTextChecker().completions" to get possible completions for the text typed so far. I'm looking for something similar in Android.

I saw this answer from 5 years ago which seems to imply that you have to write your own code, and include your own dictionary. Is this still true? Does anyone know of project (and a dictionary) which can be freely used (or at least have some code to parse and organize the dictionaries referred to), or do I have to write my own dictionary and all the code too?

Seems unlikely so much work would be needed to duplicate a simple call in iOS, but I have not found any examples except many many examples of AutoCompleteTextView with a tiny dictionary of 5 fruit or 10 countries.


Solution

  • Well, I really can't find a way to do this - so I simply imported a list of the most commonly used couple of thousand words in English into my app (comma separated), then have some code like this:

        // let's create a list of 1000 words
        String thousandWords = resources.getString(R.string.words1000list);
        String[] list = thousandWords.split(",");
        words = Arrays.asList(list);
    

    and I wrote some code like this (uses Java 8):

    public class WordPredicates {
    
        public static Predicate<String> startsWith(final String prefix) {
            return p -> p.startsWith(prefix);
        }
    
        public static List<String> getCandidates (List<String> wordsList, Predicate<String> predicate) {
            return wordsList.stream().filter(predicate).collect(Collectors.<String>toList());
        }
    }
    

    Then whenever I have some text I want possible completions I simply call:

        List<String> completions = WordPredicates.getCandidates(words, WordPredicates.startsWith(word));
    

    Works a treat