简体   繁体   中英

How to query UserDictionary content provider on Android?

I can't seem to find any good example code of how to query the UserDictionary content provider given a word. My query looks like:

Cursor cur = getContentResolver().query(
    UserDictionary.Words.CONTENT_URI,
    new String[] {Words._ID, Words.WORD},
    Words.WORD + "=?",
    new String[] {"test"},
    null);

I have also tried not specifying a query as well as not specifying a projection and the cursor is always empty. I have included android.permission.READ_USER_DICTIONARY in my manifest.

Precondition: Make sure you have appropriate words in UserDictionary at
Settings -> Language & Input -> Personal dictionary .

Sample sql query which searches for words containing SO in user dictionary and it's equivalent Android code sample. Notice the usage of ? to be replaced by args .

SQL query:

SELECT UserDictionary.Words._ID, UserDictionary.Words.WORD FROM UserDictionary.Words.CONTENT_URI WHERE UserDictionary.Words.WORD LIKE "%SO%

Equivalent Code:

String[] columns = {UserDictionary.Words._ID, UserDictionary.Words.WORD};
String condition = UserDictionary.Words.WORD  + " LIKE ? ";
// ? in condition will be replaced by `args` in order.
String[] args = {"%SO%"};

ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI, columns, condition, args, null);
//Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI, projection, null, null, null); - get all words from dictionary
if ( cursor != null ) {
    int index = cursor.getColumnIndex(UserDictionary.Words.WORD);
    //iterate over all words found
    while (cursor.moveToNext()) {
        //gets the value from the column.
        String word = cursor.getString(index);
        Log.i(TAG, "Word found: " + word);
    }
}

Permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>

Try this

final String[] QUERY_PROJECTION = {
  UserDictionary.Words._ID,
  UserDictionary.Words.WORD
};
Cursor cursor = getContentResolver()
            .query(UserDictionary.Words.CONTENT_URI, QUERY_PROJECTION, "(locale IS NULL) or (locale=?)", 
            new String[] { Locale.getDefault().toString() }, null);

I have not tested this, just a suggestion

Starting on API 23, the user dictionary is only accessible through IME and spellchecker. https://developer.android.com/reference/android/provider/UserDictionary.html

android.permission.READ_USER_DICTIONARY permission is no longer available in M

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM