Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query UserDictionary content provider on Android?

Tags:

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.

like image 786
user1005715 Avatar asked Nov 26 '11 22:11

user1005715


2 Answers

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

like image 71
binary Avatar answered Nov 15 '22 00:11

binary


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"/>

like image 37
kiranpradeep Avatar answered Nov 14 '22 23:11

kiranpradeep