如何快速插入ContentResolver的大量项目

时间:2014-03-04 17:07:56

标签: android android-sqlite android-contentresolver

我正在尝试以批量(数万字)为用户词典添加单词。

我试过

Scanner scanner = new Scanner(file);
                int counter = 0;
                while(scanner.hasNextLine()) {
                    String word = scanner.nextLine();
                    UserDictionary.Words.addWord(getBaseContext(), word, 255, null, Locale.getDefault());
                    setProgress((float) counter++ * 100 / linesCount);
                }

我也尝试过bulkinsert

ArrayList<String> words = new ArrayList<String>(capacity);
            int counter = 0;
            while(scanner.hasNextLine()) {
                words.add(scanner.nextLine());
                if (words.size() >= capacity) {
                    MyUserDictionary.addWords(getBaseContext(), words, Locale.getDefault());
                    words.clear();
                    setProgress((float) counter * 100 / linesCount);
                }
                counter++;
            }
            if (!words.isEmpty()) {
                MyUserDictionary.addWords(getBaseContext(), words, Locale.getDefault());
            }

我尝试过applyBatch。

所有这些方法都会导致运行时间过长。

我知道sqlite可以在事务上做得更好。

你知道更快的方法吗?

EDIT1:

  final ContentResolver resolver = context.getContentResolver();

        final int COLUMN_COUNT = 5;

        List<ContentValues> valueses = new ArrayList<ContentValues>(words.size());
        for (String word: words) {
            ContentValues values = new ContentValues(COLUMN_COUNT);
            values.put(UserDictionary.Words.WORD, word);
            values.put(UserDictionary.Words.FREQUENCY, DEFAULT_FREQUENCY);
            values.put(UserDictionary.Words.LOCALE, null == locale ? null : locale.toString());
            values.put(UserDictionary.Words.APP_ID, 0); // TODO: Get App UID
            values.put(UserDictionary.Words.SHORTCUT, "");
            valueses.add(values);
        }
        resolver.bulkInsert(UserDictionary.Words.CONTENT_URI, valueses.toArray(new ContentValues[valueses.size()]));

0 个答案:

没有答案