2011-11-26 47 views
7

我似乎無法找到任何好的示例代碼如何查詢UserDictionary內容提供商給定的單詞。我的查詢看起來像:如何在Android上查詢UserDictionary內容提供者?

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

我也試過沒有指定查詢以及沒有指定投影和遊標始終爲空。我在清單中包含了android.permission.READ_USER_DICTIONARY

+0

如果「測試」是不是在UserDictionary,那麼就會使光標空。 – Suragch

回答

1

試試這個

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); 

我沒有測試過這一點,只是一個建議

0

前提條件:確保你有適當的UserDictionary在的話
Settings - >Language & Input - >Personal dictionary

樣品SQL查詢,其搜索包含在用戶字典SO字和它的等效的Android代碼示例。注意?的用法被替換爲args

SQL查詢:

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

等效代碼:

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); 
    } 
} 

權限在AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>

相關問題