gpt4 book ai didi

android - ContentValues 数组中的重复 ContentValues

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:53 24 4
gpt4 key购买 nike

对此有什么帮助吗,确保它很简单但看不到它。

对内容提供者 (UserDictionary) 执行 bulkInsert,但所有插入都具有相同的“单词”值。问题是 ContentValues 数组。这是我的一些测试代码:

  public void mClick(View v){

int batchSize = 25;
ContentValues[] mValueArray = new ContentValues[batchSize];
List<ContentValues>mValueList = new ArrayList<ContentValues>();
ContentValues mNewValues = new ContentValues();

mNewValues.put(UserDictionary.Words.APP_ID, this.getPackageName());
mNewValues.put(UserDictionary.Words.LOCALE, "en");
mNewValues.put(UserDictionary.Words.FREQUENCY, "255");
mNewValues.put(UserDictionary.Words.WORD, "WORD1");

mValueList.add(mNewValues);

mNewValues.put(UserDictionary.Words.APP_ID, this.getPackageName());
mNewValues.put(UserDictionary.Words.LOCALE, "en");
mNewValues.put(UserDictionary.Words.FREQUENCY, "255");
mNewValues.put(UserDictionary.Words.WORD, "WORD2");

mValueList.add(mNewValues);

mValueArray = new ContentValues[mValueList.size()];
mValueList.toArray(mValueArray);

Log.i(TAG,mValueList.toString());
Log.i(TAG,mValueArray[0].toString());
Log.i(TAG,mValueArray[1].toString());


}

并且从log中可以看出mValueArray存在重复值。

02-22 12:33:51.060: I/log(859): [appid=dictionary word=WORD2 frequency=255 locale=en, appid=dictionary word=WORD2 frequency=255 locale=en]
02-22 12:33:51.070: I/log(859): appid=dictionary word=WORD2 frequency=255 locale=en
02-22 12:33:51.070: I/log(859): appid=dictionary word=WORD2 frequency=255 locale=en

显然,我在向数组添加值时做错了。谁能帮我?谢谢

最佳答案

您正在修改同一个对象。这应该可以正常工作:

 public void mClick(View v){

int batchSize = 25;
ContentValues[] mValueArray = new ContentValues[batchSize];
List<ContentValues>mValueList = new ArrayList<ContentValues>();
ContentValues mNewValues = new ContentValues();

mNewValues.put(UserDictionary.Words.APP_ID, this.getPackageName());
mNewValues.put(UserDictionary.Words.LOCALE, "en");
mNewValues.put(UserDictionary.Words.FREQUENCY, "255");
mNewValues.put(UserDictionary.Words.WORD, "WORD1");

mValueList.add(mNewValues);

mNewValues = new ContentValues();
mNewValues.put(UserDictionary.Words.APP_ID, this.getPackageName());
mNewValues.put(UserDictionary.Words.LOCALE, "en");
mNewValues.put(UserDictionary.Words.FREQUENCY, "255");
mNewValues.put(UserDictionary.Words.WORD, "WORD2");

mValueList.add(mNewValues);

mValueArray = new ContentValues[mValueList.size()];
mValueList.toArray(mValueArray);

Log.i(TAG,mValueList.toString());
Log.i(TAG,mValueArray[0].toString());
Log.i(TAG,mValueArray[1].toString());


}

关于为什么您的代码不起作用的更多解释:当您使用 add() 时,您将对象 reference(指针)保存在 < em>列表。它不复制对象。当您稍后修改同一个对象时,列表 中的引用仍然指向这个对象,因此您也在修改那个对象。您只有 2 个对同一个对象的引用。

关于android - ContentValues 数组中的重复 ContentValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9395021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com