将单词添加到用户词典并从词典中检索它们

时间:2013-08-08 09:23:58

标签: android

我的应用程序中有很少的edittexts,用户输入公司名称,客户名称,目的....各种事物。现在我想以编程方式将这些单词添加到字典中,因此他们不必每次都重新输入整个单词,而是字典应该在他们开始输入时建议单词。

我在网上搜索了相同的内容,我得到了类似

的内容
UserDictionary.Words.addWord(getActivity(), et_client_name.getText().toString(), 1, "", locale);

我们需要为该应用授予两项权限:

<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY"/>
<uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>

但我的问题是:一旦我使用上述声明添加单词;如何从字典中检索它并在用户开始输入时立即建议用户。

对任何好的教程的任何帮助或参考表示赞赏!

1 个答案:

答案 0 :(得分:2)

我设法找到了我自己的问题的解决方案....回答这个问题,希望它可以帮助某人作为同一类问题的参考:

public class HomeActivity extends Fragment implements TextWatcher {

    String itemClientName[] = {};
    ArrayAdapter<String> clientNameAdapter;
    ArrayList<String> clientNameList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AutoCompleteTextView et_client_name = (AutoCompleteTextView) findViewById(R.id.et_client_name);
        getFromDictionary();
        suggestClientName();
        et_client_name.addTextChangedListener(this);
    }

    public void getFromDictionary() {
        System.out.println("Inside getFromDictionary");
        ContentResolver resolver = getActivity().getContentResolver();
        String[] projection = new String[]{BaseColumns._ID, UserDictionary.Words.WORD};
        cursor = resolver.query(UserDictionary.Words.CONTENT_URI, projection, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                long id = Integer.parseInt(cursor.getString(0));
                word = cursor.getString(1);
                // Prepare list for autoCompletion
                System.out.println("Inside prepareMyList" + word);
                if (!clientNameList.contains(word))
                    clientNameList.add(word);
                System.out.println("clientNameList::" + clientNameList);
                System.out.println("Word from dictionary is::" + word);
                // do something meaningful
            } while (cursor.moveToNext());
        }
    }

    public void suggestClientName() {
        String newAdd1 = et_client_name.getText().toString();
        if (!clientNameList.contains(newAdd1)) {
            clientNameList.add(newAdd1);
            // update the autocomplete words
            clientNameAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_dropdown_item_1line, clientNameList);
            et_client_name.setAdapter(clientNameAdapter);
        }
        // display the words in myList for your reference
        String s = "";
        for (int i = 0; i < clientNameList.size(); i++) {
            s += clientNameList.get(i) + "\n";
        }
    }
}