出于某种原因,当我尝试插入多个数据时,我会得到每行4个重复项。我尝试了cv.clear(),我也尝试了cv = new ContentValues(),但我不知道是什么导致它插入4次。 for循环当然只运行两次,它调用db.insert两次。但我认为这与我看不到的ContentValues有关。
在MainActivity.java中
DBAdapter db = new DBAdapter(this);
db.open();
String[] skuArray = { "1234", "4569" };
String[] nameArray = { "Something", "Anything" };
String[] descriptionArray = { "It is something", "It is anything" };
String[] costArray = { "$5.00", "$10.00"};
for (int i = 0; i < skuArray.length; i++) {
String sku = skuArray[i];
String name = nameArray[i];
String description = descriptionArray[i];
String cost = costArray[i];
db.insert(sku, name, description, cost;
}
在DBAdapter.java中插入()方法
public void insert(String sku, String name, String description, String cost) {
try {
ContentValues cv = new ContentValues();
// Insert into ITEM_TABLE
cv.put(ITEM_SKU, sku);
cv.put(ITEM_NAME, name);
cv.put(ITEM_DESCRIPTION, description);
db.insert(ITEM_TABLE, null, cv);
// Insert into PRICE_TABLE
cv = new ContentValues();
cv.put(PRICE_SKU, sku);
cv.put(PRICE_COST, cost);
db.insert(PRICE_TABLE, null, cv);
} catch (Exception e) {
e.printStackTrace();
}
}
DBAdapter.java loadAllItemsQuery()方法
public void loadAllItemsQuery() {
try {
String SELECT_ITEM_QUERY = "SELECT " + ITEM_SKU + ", " + ITEM_NAME + ", " + ITEM_DESCRIPTION + ", " + PRICE_COST + " FROM " + ITEM_TABLE + " INNER JOIN " + PRICE_TABLE;
Cursor cursor = db.rawQuery(SELECT_ITEM_QUERY, null);
cursor.moveToFirst();
do {
skuArray[cursor.getPosition()] = cursor.getString(0);
nameArray[cursor.getPosition()] = cursor.getString(1);
descriptionArray[cursor.getPosition()] = cursor.getString(2);
priceArray[cursor.getPosition()] = cursor.getString(3);
Log.d("loadAllItemsQuery()", "Count row: " + cursor.getCount());
Log.d("loadAllItemsQuery()", "Current row position: " + cursor.getPosition());
Log.d("loadAllItemsQuery()", skuArray[cursor.getPosition()]);
} while (cursor.moveToNext());
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果:
Count row: 8
Current row position: 0
sku: 1234
Count row: 8
Current row position: 1
sku: 1234
Count row: 8
Current row position: 2
sku: 1234
Count row: 8
Current row position: 3
sku: 1234
Count row: 8
Current row position: 4
sku: 4569
Count row: 8
Current row position: 5
sku: 4569
Count row: 8
Current row position: 6
sku: 4569
Count row: 8
Current row position: 7
sku: 4569
答案 0 :(得分:0)
问题可能与您的加入有关,导致它每次返回4次。
试试这个:
String SELECT_ITEM_QUERY = "SELECT DISTINCT " + ITEM_SKU + ", " + ITEM_NAME + ", " + ITEM_DESCRIPTION + ", " + PRICE_COST + " FROM " + ITEM_TABLE + " INNER JOIN " + PRICE_TABLE;
更好的选择:查看查询并更恰当地构建它,而不是选择distinct。还尝试打印所有阵列。如果其他字段中的值存在差异,您仍然会继续获得超过预期的行数。 AND 检查您的数据是否合理。查询可能是正确的,但数据也可能导致问题。