[英]Find missing value from ArrayList in Java
我有一个问题,其中缺少 ArrayList 中的值。 当我 toast listCartItemValues.toString()
,结果根据现有数据是正确的。 但是当我在 Model DataItemCart 中设置listCartItemValues
然后我敬酒时,缺少其中一个值,那就是 Starlight。
我的 API :
{
"data": [
{
"cart_item_values": [
{
"attribute_name": "color",
"attribute_value": "Starlight"
},
{
"attribute_name": "size",
"attribute_value": "XL"
}
]
},
{
"cart_item_values": [
{
"attribute_name": "size",
"attribute_value": "10"
}
]
}
],
}
我获取cart_item_values
代码:
private List<CartItemValuesItem> listCartItemValues;
for (int a = 0; a < data.length(); a++) {
JSONObject dataJSONObject = data.getJSONObject(a);
final DataItemCart dataItemCart = new DataItemCart();
final CartItemValuesItem cartItemValuesItem = new CartItemValuesItem();
JSONArray arrayCartItemValues = dataJSONObject.optJSONArray("cart_item_values");
for (int b = 0; b < arrayCartItemValues.length(); b++) {
JSONObject cartItemJsonObject = arrayCartItemValues.optJSONObject(b);
listCartItemValues = new ArrayList<>();
cartItemValuesItem.setAttributeName(cartItemJsonObject.getString("attribute_name"));
cartItemValuesItem.setAttributeValue(cartItemJsonObject.getString("attribute_value"));
listCartItemValues.add(cartItemValuesItem);
Toast.makeText(mContext, "value : "+ listCartItemValues.toString(), Toast.LENGTH_SHORT).show();
// this list contain Starlight, XL, and 10
}
dataItemCart.setCartItemValues(listCartItemValues);
Toast.makeText(mContext, "data : "+ dataItemCart.getCartItemValues.toString(), Toast.LENGTH_SHORT).show();
// but this list contain XL and 10. Starlight is missing
}
如何从 ArrayList 中查找缺失值并将缺失值输入到dataItemCart.setCartItemValues
?
移动"final DataItemCart dataItemCart = new DataItemCart();" 在第一个 For 循环之外。
移动“listCartItemValues = new ArrayList<>();” 在第二个 For 循环之外。
这是修改后的代码。
private List<CartItemValuesItem> listCartItemValues;
final DataItemCart dataItemCart = new DataItemCart();
for (int a = 0; a < data.length(); a++) {
JSONObject dataJSONObject = data.getJSONObject(a);
final CartItemValuesItem cartItemValuesItem = new CartItemValuesItem();
JSONArray arrayCartItemValues = dataJSONObject.optJSONArray("cart_item_values");
listCartItemValues = new ArrayList<>();
for (int b = 0; b < arrayCartItemValues.length(); b++) {
JSONObject cartItemJsonObject = arrayCartItemValues.optJSONObject(b);
cartItemValuesItem.setAttributeName(cartItemJsonObject.getString("attribute_name"));
cartItemValuesItem.setAttributeValue(cartItemJsonObject.getString("attribute_value"));
listCartItemValues.add(cartItemValuesItem);
Toast.makeText(mContext, "value : "+ listCartItemValues.toString(), Toast.LENGTH_SHORT).show();
// this list contain Starlight, XL, and 10
}
dataItemCart.setCartItemValues(listCartItemValues);
Toast.makeText(mContext, "data : "+ dataItemCart.getCartItemValues.toString(), Toast.LENGTH_SHORT).show();
// but this list contain XL and 10. Starlight is missing
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.